英文:
Adding odd numbers in Bash
问题
我正在尝试创建一个程序,根据用户输入的数字来相加奇数。到目前为止,这是我的代码。它出现了错误,我不确定接下来该怎么办。
echo "你想要相加多少个数字?"
read n
i=1
sum=0
echo "奇数是:"
while [ $i -le $n ]
do
odd=$((2 * i - 1))
echo -n $odd
sum=$((sum + odd))
((i++))
done
echo "总和是:$sum"
希望这可以帮助你找到问题并解决它。
英文:
I am trying to create a program that will add odd numbers given an user input. So far this is what I have. It's failing, and I am not sure where to go from here.
echo "How many numbers would you like to add?"
read n
i=1
sum=0
echo "Odd numbers are:"
while [ i -le $n ]
do
odd=(2*i-1)
echo -n $odd
sum=(sum+odd)
((i++))
done
echo "Sum is: $sum"
答案1
得分: 1
我已成功使用以下脚本使其工作:
echo "您想要添加多少个数字?"
read n
echo "奇数是:"
let i=1
let sum=0
while [ $i -le $n ]
do
let odd=2*i-1
echo "$odd"
sum=$((sum+odd))
((i++))
done
echo "总和为:$sum"
有一些地方需要修正语法。
例如,用于评估算术表达式的语法是$((expr))
。
有些变量前面可能需要$
。
以下是脚本的输出:
% chmod +x script.sh
% ./script.sh
您想要添加多少个数字?
5
奇数是:
1
3
5
7
9
总和为:25
英文:
I was able to get it to work with this script:
echo "How many numbers would you like to add?"
read n
echo "Odd numbers are:"
let i=1
let sum=0
while [ $i -le $n ]
do
let odd=2*i-1
echo "$odd"
sum=$((sum+odd))
((i++))
done
echo "Sum is: $sum"
There were some places where the syntax had to be corrected.
For example, the syntax for evaluating arithmetical expressions is $((expr))
.
And the $
might be needed in front of some variables.
Here is the output of the script:
% chmod +x script.sh
% ./script.sh
How many numbers would you like to add?
5
Odd numbers are:
1
3
5
7
9
Sum is: 25
答案2
得分: 1
你也可以使用一个 for
循环
#! /bin/bash
echo "你想要添加多少个数字?"
read n
echo "奇数数字为:"
for (( i=1; i<=2*n; sum+=i,i+=2 )); do
echo $i
done
echo "总和是:$sum"
英文:
You can also use a for
loop
#! /bin/bash
echo "How many numbers would you like to add?"
read n
echo "Odd numbers are:"
for (( i=1; i<=2*n; sum+=i,i+=2 )); do
echo $i
done
echo "Sum is: $sum"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论