这是我到目前为止所做的:
echo "Please enter your first number: "
read a
echo "Second number: "
read b
(等) 这很好,但是当我尝试为sum average和product设置函数时,我遇到了一些问题。
这就是我的尝试:
sum= ($a + $b + $c + $d + $e)
avg= ($sum / 5) #The five was showing up in red text
prod= ($a * $b * $c * $d * $e)
echo "The sum of these numbers is: " $sum
echo "The average of these numbers is: " $avg
echo "The product of these numbers is: " $prod
但是当我运行它(在我输入数字1,2,3,4,5之后)后,我得到了回复:
The sum of these numbers is: 1 + 2 + 3 + 4 + 5
The average of these numbers is: 1 + 2 + 3 + 4 + 5 / 5
The product of these numbers is: 1 * 2 * 3 * 4 * 5
所以我的问题是我如何在()
中计算这些函数感谢任何帮助,谢谢。
答案 0 :(得分:1)
read N
i=1
sum=0
while [ $i -le $N ]
do
read num
sum=$((sum + num))
i=$((i + 1))
done
avg1=$(echo $sum / $N | bc -l);
echo "scale = 3; $avg1 / 1" | bc -l
此代码对我有用。感谢-oogy。对于这一部分
echo“ scale = 3; $ avg1 / 1” | bc -l`
答案 1 :(得分:0)
试试这个:
#!/bin/bash
echo "Please enter your first number: "
read a
echo "Second number: "
read b
echo "Third number: "
read c
echo "Fourth number: "
read d
echo "Fifth number: "
read e
sum=$(($a + $b + $c + $d + $e))
avg=$(echo $sum / 5 | bc -l )
prod=$(($a * $b * $c * $d * $e))
echo "The sum of these numbers is: " $sum
echo "The average of these numbers is: " $avg
echo "The product of these numbers is: " $prod
唯一的问题是sum
,avg
,prod
部分的一些小的语法问题。
平均值不像其他计算那样完成,因为它可能返回浮点数。此号码通过管道传输至bc
并存储在avg
。
当我运行这个程序时,我得到了结果:
Please enter your first number:
2
Second number:
2
Third number:
2
Fourth number:
3
Fifth number:
2
The sum of these numbers is: 11
The average of these numbers is: 2.20000000000000000000
The product of these numbers is: 48