Having trouble with casting: (int)

Hi--

I have 2 doubles x and y. When I divide x/y I dont get the result I am hoping to get.

Here is the printf command I am using and the output I am getting:

command:

printf("%3.10f %3.2f %3.12f %d\n",x,y,x/y,(int)(x/y));

output:

1.0000000000 0.10 10.000000000000 9

To me, x/y ought to be 10 and so not sure why (int)(x/y) is producing 9 instead of 10.

Can someone help me understand this surce of this problem please?
You get these error because x/y results in slightly less than 10 (it surely is less than 10^-12 off, otherwise the other result wouldn't show as 10.000000000000), probably due to the usual floating point math rounding errors.

use this you will get the right result
printf("%3.10f\t %3.2f\t %3.12f\t %d\n",x,y,x/y,(int)(round(x/y)));

because casting to int doesn't round a double to the nearest integer but the conversion to int is a brutal truncation, thus, even if it's 9.99999999999999... you get 9 as a result.
I see. Thanks very much.
Topic archived. No new replies allowed.