Ubuntu Shell脚本,用于查找五个数字的总和平均值和乘积
这就是我到目前为止所做的:Ubuntu Shell脚本,用于查找五个数字的总和平均值和乘积,ubuntu,scripting,Ubuntu,Scripting,这就是我到目前为止所做的: echo "Please enter your first number: " read a echo "Second number: " read b (等等) 这很好,但当我尝试设置求和平均值和乘积的函数时,遇到了一些问题 这就是我所尝试的: sum= ($a + $b + $c + $d + $e) avg= ($sum / 5) #The five was showing up in red text prod= ($a * $b * $c * $d * $
echo "Please enter your first number: "
read a
echo "Second number: "
read b
(等等)
这很好,但当我尝试设置求和平均值和乘积的函数时,遇到了一些问题
这就是我所尝试的:
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
所以我的问题是如何让这些函数在()
感谢您的帮助。尝试以下方法:
#!/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
这个代码对我有用。多亏了-oogy。这部分
回声“标度=3;$avg1/1”| bc-l`
伟大的如果这个答案对你有效,请确保单击该答案上的复选标记,这样这个问题就可以标记为已回答。求和和和乘积有效,但我在表达式中得到了平均值的语法错误。在那之后,我尝试了这个,并让它工作。平均值=$($总和/5))
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