In this post, we will solve Compute the Average HackerRank Solution. This problem (Compute the Average) is a part of Linux Shell series.
Task
Given N integers, compute their average, rounded to three decimal places.
Input Format
The first line contains an integer, N.
Each of the following N lines contains a single integer.
Output Format
Display the average of the N integers, rounded off to three decimal places.
Input Constraints
- 1 <= N <= 500
- -10000 <= x <= 10000 (x refers to elements of the list of integers for which the average is to be computed)
Sample Input
4
1
2
9
8
Sample Output
5.000
Explanation
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`
Note: This problem (Compute the Average) is generated by HackerRank but the solution is provided by CodingBroz. This tutorial is only for Educational and Learning purpose.