0

这是我到目前为止所拥有的:

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

所以我的问题是如何让这些函数在 ()

任何帮助表示赞赏,谢谢。

4

2 回答 2

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。对于这部分

回声“比例= 3;$ avg1 / 1”| 公元前-l`

于 2019-11-21T06:48:33.127 回答
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
于 2013-10-11T23:03:33.170 回答