在Bash中添加奇数数字

huangapple go评论51阅读模式
英文:

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 &quot;How many numbers would you like to add?&quot;
read n

echo &quot;Odd numbers are:&quot;
for (( i=1; i&lt;=2*n; sum+=i,i+=2 )); do 
    echo $i
done
echo &quot;Sum is: $sum&quot;

huangapple
  • 本文由 发表于 2023年2月27日 12:21:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75576752.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定