In this post, we will solve Compute the Average HackerRank Solution. This problem (Compute the Average) is a part of Linux Shell series.
Given N integers, compute their average, rounded to three decimal places.
The first line contains an integer, N.
Each of the following N lines contains a single integer.
Display the average of the N integers, rounded off to three decimal places.
- 1 <= N <= 500
- -10000 <= x <= 10000 (x refers to elements of the list of integers for which the average is to be computed)
4 1 2 9 8
The ‘4’ in the first line indicates that there are four integers whose average is to be computed.
The average = (1 + 2 + 9 + 8)/4 = 20/4 = 5.000 (correct to three decimal places).
Please include the zeroes even if they are redundant (e.g. 0.000 instead of 0).
Solution – Compute the Average – HackerRank Solution
#!/bin/bash #Easier way is to do using for loop read num ctr=$num sum=0 while [ $ctr -gt 0 ] do read x sum=$((sum + x)) ctr=$((ctr - 1)) done printf "%.3f\n" `echo "$sum/$num" | bc -l`