-
weird problem!
i have a very weird problem with a float.
i've read from a file a number:
423.230000
if i:
Code:
printf("%f ",tmp[*n].val+x);
it prints me:
423.230000 that is ok!
tmp[*n].val is a float component of a structure containing the integer (423.00000) and x is a float containing 0.230000
but if i do:
Code:
tmp[*n].val+=x;
printf("%f ",tmp[*n].val);
it prints me:
423.230011
Where does the 0.000011 comes from ?
This problem occurs within a function!
How can I fix it ?
Thank you!
-
> printf("%f ",tmp[*n].val+x);
Both get promoted to double, before the addition is performed and the result passed to printf
> tmp[*n].val+=x;
>printf("%f ",tmp[*n].val);
The calculation is done using float, and it only becomes a double when you pass it to printf.
> 423.230011
floats have 6 decimal digits of precision, so you can only rely on 423.230
The remainder of the result is random noise.
The reason it works for doubles is they have about 15 decimal digits of precision.
> How can I fix it ?
Always use doubles unless you have a specific reason not to.
-
yep... that solved it. Thank you!