数组中的值的减法

数组中的值的减法

我正在使用一个数组来尝试减法。然而,当我的脚本只是给我数组的总数时,前面有一个负号。有什么建议么?

elif [ "$OP" = "Subtraction" ]; then
    echo "Please enter the number of values you would like to perform $OP"
    read num
        while [[ $num -gt $i ]]; do
            echo "Enter your value"
            read value
            let total=$total-$value
            let valuearr[$i]=$value
            let i=$i+1
        done
        echo "You entered ${valuearr[*]}, and asked me to perform $OP. The answer is $total."

答案1

如果我事先设置i=1并将total=0测试更改为-ge那么它似乎有效:

OP=Subtraction
if [ "$OP" = "Subtraction" ]; then
    echo "Please enter the number of values you would like to perform $OP"
    read num
    i=1
    total=0
        while [[ $num -ge $i ]]; do
            echo "Enter your value"
            read value
            let total=$total-$value
            let valuearr[$i]=$value
            let i=$i+1
        done
        echo "You entered ${valuearr[*]}, and asked me to perform $OP. The answer is $total."
fi

$ bash x
Please enter the number of values you would like to perform Subtraction
3
Enter your value
1
Enter your value
2
Enter your value
4
You entered 1 2 4, and asked me to perform Subtraction. The answer is -7.

如果不设置,i=1您将错过${valuearr[*]}输出的一个元素。 total=0这只是很好的代码,以防变量在其他地方使用。

显然 0-1-2-4 == -7 所以结果是正确的。

相关内容