Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rounding off in bash [duplicate]

I was taking a challenge on hackerrank . The aim is:

read (int) N; then read N integers and print their avg to three decimal places.

Here's the code:

#!/bin/bash
#file name:rdlp.sh
read N
s=0
i=1
while (($i<=$N))
     do
           read a
           s=$((s+a))
           i=$((i+1))
     done
s=$s/$N
echo  "scale=3;$s"|bc -l
fi

When I run the code for some inputs:

3 #(value of N)
4 #(N = 3 integers)
4
3

Then the output is 3.666, but it should be 3.667.

So the QUESTION is that is there anyway to get it right (correct rounding off), or does it work like that only?

(the question came off when the above code was run for Testcase2 of the challenge at hackerrank)

like image 749
Ra Phi Avatar asked Sep 12 '26 07:09

Ra Phi


1 Answers

bc rounds down with scale=x.
You can printf:

$ printf "%.3f\n" $(echo  "scale=1000; 11/3"|bc -l)
3.667

or some tricky bc by adding 0.0005:

$ echo  "scale=1000; v=11/3; v=v+0.0005; scale=3; v/1" | bc -l
3.667
like image 175
KamilCuk Avatar answered Sep 13 '26 21:09

KamilCuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!