compute Average in Bash [closed]

2019-06-14 20:19发布

Problem Statement

Given N integers, compute their average, correct to three decimal places.

Input Format The first line contains an integer N. This is followed by N integers, each on a new line.

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

explaination

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 (eg. 0.000 instead of 0).

1条回答
一纸荒年 Trace。
2楼-- · 2019-06-14 20:37

You can use this awk command:

awk 'NR==1{n=$1;next} {s+=$1} END{printf "%.3f\n", s/n}' file
5.000
查看更多
登录 后发表回答