Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - Calculate the Average of Numbers Inputted

Need help with Linux Bash script. Essentially, when run the script asks for three sets of numbers from the user and then calculates the numbers inputted and finds the average.

#!/bin/bash
echo "Enter a number: "
read a
   while [ "$a" = $ ]; do

echo "Enter a second set of numbers: "
read b
b=$
   if [ b=$ ]

Am I going about this wrong?

like image 273
user3089320 Avatar asked Dec 11 '13 02:12

user3089320


2 Answers

Still not sure what you want a to be. But I think you can just loop 3 times. Then each iteration get a set of numbers, and add them up and keep track of how many you have. So something like below. (note $numbers and $sum are initialized to 0 automatically)

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

Where example output would be

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
like image 144
Reinstate Monica Please Avatar answered Sep 28 '22 15:09

Reinstate Monica Please


If I understood you correctly, the following code will do what you asked:

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

Note - I left count as a separate variable so you can easily extend this code.

The use of bc allows floating point arithmetic (not built in to bash); scale=2 means "two significant figures".

Sample run:

Enter three numbers:
3 4 5
The mean of these  3  values is  4.00
like image 38
Floris Avatar answered Sep 28 '22 15:09

Floris