小编use*_*680的帖子

Linux bash.for loop和function,用于添加数字

我正在Linux中学习bash脚本,我想解决一个我认为很容易但我无法解决的问题.

我想插入数字作为参数,例如:

sh script.sh 5
Run Code Online (Sandbox Code Playgroud)

如果我插入5(1 + 2 + 3 + 4 + 5)= 15,我想得到结果15

我想用功能来解决它​​.

n=$1
result=0
j=0

ADD(){
    result=`expr $result + $j`
}

#for (( i=1; i<=$n; i++ ))
for i in {0..$n..1}
do 
    ADD
    j=`expr $j + $1`
done 

echo $result
Run Code Online (Sandbox Code Playgroud)

每当我想添加数字时,我想调用函数进行添加.我不知道我是否想象得对.而且我不知道如何使用for循环.我已经尝试了两种不同的for循环,我认为它们无法正常工作.

linux bash for-loop function

9
推荐指数
1
解决办法
3万
查看次数

是否有可能在阵列中存储1000万个数字?

我想知道你可以在阵列中存储多少个数字?

srand (time(NULL));
int array[10000000];
for(int i = 0; i < 10000000; i++){
    array[i] = (rand() % 10000000) + 1;
}
Run Code Online (Sandbox Code Playgroud)

每次我想在数组中存储10.000.000个数字时我的程序崩溃了(Eclipse).我甚至试过Visual Studio并且它崩溃了.

所以我想知道我可以在数组中存储多少个数字或者我的代码有问题?

c++ arrays random

7
推荐指数
2
解决办法
1万
查看次数

Linux bash脚本,用于添加数字的递归

我想弄清楚递归在bash脚本中是如何工作的.

我想插入数字作为参数:

sh script.sh 4
Run Code Online (Sandbox Code Playgroud)

结果将是(1 + 2 + 3 + 4)= 10

这就是我写的,在我脑海中工作得很好,但不能使它工作.

n=$1
j=1
result=0

recursion(){ 
    result=`expr $result + $j` 
    j=`expr $j + 1`

    if [ "$n" -gt 0 ]; then
        recursion      #is this how you do recursion?
        n=`expr $n - 1
    else
        echo $result 
    fi
}

recursion
Run Code Online (Sandbox Code Playgroud)

我想我想象得对,但可能我错了.

linux bash recursion

3
推荐指数
1
解决办法
1312
查看次数

标签 统计

bash ×2

linux ×2

arrays ×1

c++ ×1

for-loop ×1

function ×1

random ×1

recursion ×1