-
Casting Problems
#include <stdio.h>
main()
{
long l;
long l_corr,l_corr2;
double d = 2.03;
l = d*100;
printf( " l = %ld\n",l);
}
Pls can you explain me why does l prints 202 instead of 203 .
Also if d would have been equal to 2.04 it would have printed properly as 204 .
I know the solution for this , but just wanted the reason for it !!
Thanx
-
Probably because 2.03 is really stored as 2.029999999
Which becomes 202.9999999 when you multiply by 100.0
But since you're assigning to an int, this truncates to 202, no matter how close you might be to 203.
Floats are approximations to real numbers - so you occasionally get these types of rounding errors.
-
Thanx Salem ,
May be your Right . But then why d = 2.04 works fine ??
-
That was me Salem I just forgot to Enter my user name .
I tried with 2.04 , 2.06 it gave correct results
But 2.05 gives 204 .
-
Tip: add 0.5 before converting from double to long:
Code:
l = (long)((d * 100)+0.5);
This should solve your problem.
-
Thanx
But I know the solution
l = (float) (d*100) does work ... but I wanted to know why it happens
-
>but I wanted to know why it happens
I may have read between the lines, but Salem told you why it happens. If, however, you want a truly frightening description of the details of floating-point arithmetic, try this:
http://cch.loria.fr/documentation/IE...M/goldberg.pdf
-Prelude
-
ah
ya, you better try that. prelude is right again