There is a problem in proposed solution. According to cplusplus.com, the format f
only accepts a width and no precision.
If you had controlled the return from the scanf
(what you should definitively always do - and now you know why !) you would have seen immediately the problem :
int x, cr;
float balance,y;
cr = scanf("%d %.2f",&x,&y);
if (cr != 2) {
fprintf(stderr, "Read error : cr = %d\n", cr);
}
Given any input, you will get :
Read error : cr = 1
Possible implementation with very little change :
cr = scanf("%d %f",&x,&y);
if (cr != 2) {
fprintf(stderr, "Read error : cr = %d\n", cr);
}
// should round to only two digits - within floating point accuracy
y = (((double)((int)(y * 100 + 0.5))) / 100.);
If you have a system where math.h
contains round
(not MSVC :-( ), last line is better written as (thanks to chux for proposing it) :
y = round(y * 100)/100
because above formula will fail for negative y and for y > INT_MAX / 100
If you really needed exact precision with two decimal digit, the correct way would be to do all computation as integer on long, taking the numbers multiplied by 100. I leave that as an exercise for the reader :-)