Ok so this is a hackerrank problem (https://www.hackerrank.com/challenges/bash-tutorials---arithmetic-operations). Basically, input is an arithmetic expression and I'm supposed to print out formatted answer (3 decimal places). I tried this at first
read exp
echo "scale = 3; $exp" | bc -l
It passed several tests but not the first one.
5+50*3/20 + (19*2)/7
The answer is 17.929
but my code prints out 17.928
. I tried this code instead
read exp
printf "%.3f\n" `echo $exp | bc -l`
Note: the echo part should be in backticks but I put ' ' to not confuse with block quotes. All tests passed. So what's the difference?
The reason that the two differ is that bc
always cuts off the numbers instead of rounding them. I. e. echo "scale = 3 ; 8/9" | bc
produces 0.888 instead of the correctly rounded 0.889.
Your test case evaluates to 17.928571429, which is rounded to 17.929 with your printf
approach, but cut off to 17.928 with the bc
approach.
I think the problem is scale = 3;
part. For example, if you use
printf "%.3f\n" ` echo "scale = 3 ; $exp " | bc -l`
You will get 17.928 again. So the answer is you need to set scale at least to 4 and then print it in three digit.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With