需要有关Linux Bash脚本的帮助.基本上,当运行脚本时,要求用户提供三组数字,然后计算输入的数字并找到平均值.
#!/bin/bash
echo "Enter a number: "
read a
while [ "$a" = $]; do
echo "Enter a second set of numbers: "
read b
b=$
if [ b=$]
我错了吗?
解决方法:
仍然不确定你想要的是什么.但我认为你可以循环3次.然后每次迭代都会获得一组数字,然后将它们相加并跟踪您拥有的数量.如下所示. (注意$numbers和$sum自动初始化为0)
#!/bin/bash
sum=0
numbers=0
for a in {1..3}; do
read -p $'Enter a set of numbers:\n' b
for j in $b; do
[[ $j =~ ^[0-9]+$]] || { echo "$j is not a number" >&2 && exit 1; }
((numbers+=1)) && ((sum+=j))
done
done
((numbers==0)) && avg=0 || avg=$(echo "$sum / $numbers" | bc -l)
echo "Sum of inputs = $sum"
echo "Number of inputs = $numbers"
printf "Average input = %.2f\n" $avg
示例输出将是
Enter a set of numbers:
1 2 3
Enter a set of numbers:
1 2 3
Enter a set of numbers:
7
Sum of inputs = 19
Number of inputs = 7
Average input = 2.71