i have the following very simple code –
int x=15000
int z=0.7*x
cout<<"z = "<<z<<endl;
i get the output
z=10499
but if i change it to
int z=0.7*15000
cout<<"z = "<<z<<endl;
outputs
z=10500
i understand it has something to do with z casting the result to int
but why is it different in both cases ?
thanks,
EDIT –
i’m using ubuntu’s 10.10 GCC build
int z=0.7*x;
The double-precision value 0.7 is not exactly representable as a floating-point number; its hex representation is 3fe6666666666666 on most machines, which is less than the true value 3fe6666666666666… So the double-precision result of 0.7*x is less than its true value, and is rounded down. This is correct behaviour.
int z=0.7*15000;
The compiler, on the other hand, is clever enough to see that 0.7 * 15000 is representable exactly as 7 * 1500 = 10500. So it uses the correct result, instead of the result that would be obtained by compiling the expression and executing it.