Bash - 计算输入的数字平均值

时间:2013-12-11 02:38:59

标签: linux bash numbers average

需要有关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=$ ]

我是不是错了?

4 个答案:

答案 0 :(得分:4)

仍然不确定你想要的是什么。但我认为你可以循环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

答案 1 :(得分:1)

如果我理解正确,以下代码将按您的要求执行:

#!/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

答案 2 :(得分:0)

测试值:

    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

答案 3 :(得分:0)

 #!/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