We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
reads standard input and executes SCRIPT on every line
'NR > 1 { avg += \$1; }'
for every line where NR (number of record) is greater than 1, add $1 (first word on the line) to the avg
'END {printf("%.3f",(avg*1.0/(NR-1)));}'
on the END of the input, print the average (he should probably rename the 'avg' variable to 'tot')
Use "%.3f" to get three places of precision
Use "avg*1.0" to coerce avg into a floating point number
Divide by NR-1 instead of NR because we don't want to count the initial line in the total
That about does it?
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Compute the Average
You are viewing a single comment's thread. Return to all comments →
I'll try.
awk 'SCRIPT'
reads standard input and executes SCRIPT on every line
'NR > 1 { avg += \$1; }'
for every line where NR (number of record) is greater than 1, add $1 (first word on the line) to the avg
'END {printf("%.3f",(avg*1.0/(NR-1)));}'
on the END of the input, print the average (he should probably rename the 'avg' variable to 'tot')
Use "%.3f" to get three places of precision Use "avg*1.0" to coerce avg into a floating point number Divide by NR-1 instead of NR because we don't want to count the initial line in the total
That about does it?