需要帮助编写 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=$ ]
我这样做是不是有问题?
需要帮助编写 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=$ ]
我这样做是不是有问题?
我不确定您希望什么作为变量a。但我认为您可以循环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
#!/bin/bash
echo "Enter three numbers:"
read a b c
sum=$(($a + $b + $c))
count=3
result=$(echo "scale=2; 1.0 * $sum / $count" | bc -l)
echo "The mean of these " $count " values is " $result
count
作为单独的变量留下,这样您可以轻松扩展此代码。bc
允许浮点数算术(不内置于bash); scale=2
表示“两个有效数字”。Enter three numbers:
3 4 5
The mean of these 3 values is 4.00
#!/bin/bash
echo "Enter size"
read s `#reading size of the average`
i=1 `#initializing`
sum=0 `#initializing`
echo "Enter the factors"
while [ $i -le $s ]
do
read factors
sum=$((sum + factors))
i=$((i + 1))
done
avg=$(echo $sum / $s | bc -l)
echo "Average of factors is" $avg
测试数值:
sum=200232320
total=300123123
基本的取平均值和获取百分比:
avg=$(echo "$sum / $total" | bc -l)
avg=$(echo "$avg*100" | bc -l)
printf "Average input = %.2f\n" $avg
基本的取平均值和获取百分比,具备容错能力:
# -- what if sum=0 or greater than total?
if [ $sum -eq 0 ] || [ $sum -gt $total ] ;then
avg=0
else
avg=$(echo "$sum / $total" | bc -l)
avg=$(echo "$avg*100" | bc -l)
fi
printf "Average input = %.2f\n" $avg
基本的取平均值和获取百分比:
result=$(echo "scale=6; 1.0 * $sum / $total*100" | bc -l)
printf "Average input = %.2f\n" $result
基本的取平均值和获取百分比:
result=$(echo "scale=6; 1.0 * $sum / $total*100" | bc -l)
printf "Average input = %.2f\n" $result
基本取平均并获取百分比(带容差):
# -- if sum is greater than total we have a problem add in 1.0 to address div by zero
[[ $sum -gt $total ]] && result=0 || result=$(echo "scale=6; 1.0 * $sum / $total*100" | bc -l)
printf "Average input = %.2f\n" $result
输出:
./test.sh
Average input = 66.72
Average input = 66.72
Average input = 66.72
Average input = 66.72