Issue
This is what I have so far:
echo "Please enter your first number: "
read a
echo "Second number: "
read b
(etc..) That works fine, but when I tried to set a function for sum average and product, I ran into some problems.
This is what I tried:
sum= ($a + $b + $c + $d + $e)
avg= ($sum / 5) #The five was showing up in red text
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
but when I ran it (after I inputted the numbers 1,2,3,4,5) I got this back:
The sum of these numbers is: 1 + 2 + 3 + 4 + 5
The average of these numbers is: 1 + 2 + 3 + 4 + 5 / 5
The product of these numbers is: 1 * 2 * 3 * 4 * 5
So my question is how do I get these functions to compute within the ()
Any help is appreciated, thanks.
Solution
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
Answered By - Blue Ice Answer Checked By - Candace Johnson (WPSolving Volunteer)