Reputation: 85
I don't understand why doesn't the roundf()
function from math.h
round the donation
variable, whilst it rounds livestockPM
without a problem. I need to use the rounded values for other calculations, but I'm using printf
to check if the values are correct, and it simply returns wrong values (doesn't round variable donation
). Also, the variable final
only returns values as if rounded to .00, doesn't matter what variables farmer1
,2,3 hold.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main(){
int farmer1 = 9940;
int farmer2 = 4241;
int farmer3 = 7779;
float livestockPM = (float)farmer1 / (float)farmer2;
printf("livestock: %f\n",livestockPM);
livestockPM = roundf(livestockPM * 100) / 100;
printf("livestock rounded: %f\n",livestockPM);
float donation = (float)livestockPM * (float)farmer3;
printf("donation: %f\n", donation);
donation = roundf(donation * 100.00) / 100.00;
printf("donation rounded: %f\n", donation);
float final = donation * (float)farmer2;
printf("final: %f\n", final);
return 0;
}
Output:
livestock: 2.343787
livestock rounded: 2.340000
donation: 18202.859375
donation rounded: 18202.859375
final: 77198328.000000
Anyone got any idea why? I was thinking because of multiplying float with int, but I can't seem to get it work like this. I've tried removing the (float) from integer variables, but the results were undesirable as well. Thanks.
Upvotes: 3
Views: 4920
Reputation: 153498
OP's float
is encoded using binary floating point and 18202.859375
lacks precision to take on a value that "%f"
prints as 18202.860000
.
A float
cannot represent every possible number. As a binary floating point number it can represent numbers like below. See IEEE 754 Converter, but not in between.
18202.859375
18202.86138125
When the following executes, the best possible result is again 18202.859375
.
float donation_rounded = roundf(18202.859375 * 100.00) / 100.00;
Recall that printf("%f\n", x)
prints a number rounded textually to the closest 0.000001 value.
Code could use double
, but the same problem will occur with very large numbers, but may meet OP''s immediate need. @user3386109
As OP appears to be trying to cope with money, there is no great solution in standard C. best money/currency representation goes into some of the issues.
Upvotes: 5