Bash - Calculate the Average of Numbers Inputted
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
Shell script which finds the sum average and product of five numbers
Try this:
#!/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
The only issue is some minor syntax troubles in the sum
,avg
,prod
part.
The average is not done the way the other calculations are because it may return a floating-point number. This number is piped to bc
and stored in avg
.
When I run this program, I get the results:
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
Calculate average unknown amount of input
You were doing average and sum outside the for loop in your code. I just moved them into the for loop. For every iteration , the sum and average both will change, so they have to be in the for loop.
print ("To stop entering numbers and calculate average, press CTRL+D")
print ("Enter numbers:")
i = 0
sum = 0
average = 0.0
for line in sys.stdin:
print (i, "\t", line.strip())
i = i + 1
sum += int(line.strip())
average = sum/i
print("The average of the numbers you entered is", round (average, 1),".")
Printing the sum, average values can be done outside the for loop.
This is the correct method
Program to calculate the average of unknown set of numbers in C
You are almost done. Just count
the number of elements and divide
the sum
by count
to get the average
. Here type-casting
is also required, otherwise average
of 2 and 3 will give you 2 which is incorrect.
#include <stdio.h>
int main() {
int numberEntered;
int sum = 0;
printf("Program to calculate the average of a series of numbers\n\n");
printf("Please enter the first number. Enter 0 to stop: ");
scanf("%d", &numberEntered);
int count_number = 0;
while (numberEntered != 0)
{
sum = sum + numberEntered;
count_number++;
printf("Please enter another number. Enter 0 to stop: ");
scanf("%d", &numberEntered);
}
if(count_number>0)
{printf("AVG: %f",((float)sum)/count_number);}
}
How to calculate and display the average of the 5 numbers in C++?
I Have solved my own question. As I said I am avoiding global variables, labels or go-to statements, infinite loops, and break statements to exit loops
. So, here is my answer:
Here is my code:
#include <iostream>
using namespace std;
int main() {
// Creating variables.
float v, w, x, y, z, average;
// Prompting the user to enter first number.
cout << "Please enter first number: ";
// Getting the input from the user.
cin >> v;
// Prompting the user to enter second number.
cout << "Please enter second number ";
// Getting the input from the users.
cin >> w;
// Prompting the user to enter third number.
cout << "Please enter third number ";
// Getting the input from the user.
cin >> x;
// Prompting the user to enter fourth number.
cout << "Please enter fourth number ";
// Getting the input from the user.
cin >> y;
// Prompting the user to enter fifth number.
cout << "Please enter fifth number ";
// Getting the input from the user.
cin >> z;
// Calculating the average of those user input five numbers.
average = (v + w + x + y + z) / 5;
// Displaying the total average of the five numbers entered.
cout << "The average of the five numbers is:" << average << endl;
return 0;
}
Calculating average from raw_input data in a while loop
You need to add calculating average at the end of your code.
To do that, have a count for how many times the while loop runs, and divide the answer at the end by that value.
Also, your code is adding one to the answer each time because of the line - answer = counter + anyNumber
, which will not result in the correct average. And you are missing storing the first input number, because the code continuously takes two inputs. Here is a fixed version:
num = -1
counter = 0
answer = 0
anyNumber = int(raw_input("Enter any number: "))
while anyNumber > num:
counter += 1
answer += anyNumber
anyNumber = int(raw_input("Enter another number: "))
if (counter==0): print answer #in case the first number entered was -1
else:
print answer/counter #print average
print "Good bye!"
Related Topics
Linux Perf Record: Difference Between Count (-C) and Frequency (-F) Options
How to Schedule a Cron Job to Run 4Th Week of the Year
Batch Remove Substring from Filename with Special Characters in Bash
Delete the Word Whose Length Is Less Than 2 in Bash
Difference Between Core and Core-File
Screen Command Disable the Control Key Ctrl-A to Use It in Vim
Output File Not Created When Reading Sequences
Find and Replace a Word with Another in All File Names of a Directory
Bash Syntax Error: Unaccepted Token Elif
How to to Delete a Line Given with a Variable in Sed
Which Capabilities Are Needed for Statx to Stop Giving Eperm
How to Merge Two Seperate - Yet Similar - Codebases into One Svn Rep
Environment Variable Used in Shell Script Appear Blank in Log File When Run by Cron
Why Does Autoconf Erroneously Find a Function Which Isn't Available Later
How to Cross-Compile a Qt Application for Imx6
Segmentation-Fault Error Happening with Assembly Code Program