compute Average in Bash [closed]

点点圈 提交于 2019-12-08 15:31:57

问题


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:


You can use this awk command:

awk 'NR==1{n=$1;next} {s+=$1} END{printf "%.3f\n", s/n}' file
5.000


来源:https://stackoverflow.com/questions/27653995/compute-average-in-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!