目标是有一个bash脚本,它将从1到N的整数相加,其中N由用户定义.这是我的代码:
#!/bin/bash
read -p "Enter an integer greater than zero: " N #allows the user to enter a value, which is then read from stdin and assigned to N
sum=0
for ((i=0; i<=N; i++))
do
$((sum+=i)) #add i to sum each iteration
done
echo "The sum of the numbers from 1 to $N is $sum"
Run Code Online (Sandbox Code Playgroud)
输出:
Enter an integer greater than zero: 5
-bash: 0: command not found
-bash: 1: command not found
-bash: 3: command not found
-bash: 6: command not found
-bash: 10: command not found
-bash: 15: command not found
The sum of the numbers from 1 to 5 is 15
Run Code Online (Sandbox Code Playgroud)
求和是正确的.我意识到每次迭代的总和导致某种错误(b/c 0,1,3,6 ...是每个i的求和值),但我不确定为什么或如何修理它.有没有办法在vi中调试?谢谢