开发者

a simple question about casting integers in c++

开发者 https://www.devze.com 2023-01-29 05:48 出处:网络
i have the following very simple code - int x=15000 int z=0.7*x cout<<\"z = \"<<z<<endl;

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 wh开发者_StackOverflow社区y is it different in both cases ?

thanks,

EDIT - i'm using ubuntu's 10.10 GCC build


I suppose it's because of compiler, that simplifies arithmetical expressions at the compile time.

The first expression was computed using FPU (with finite precision), and the second one: by preprocessor (with "infinite" precision). Try running the program in release mode (or with -O2), the results should be the same for both expressions.


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.


I think ruslik has the correct answer to your question.

I would just add: Always keep your calculations in either float or double until the very last moment. That way you don't lose precision.

Try changing your code to this:

double z = 0.7 * 15000.0;
cout<<"z = "<<z<<endl; // Will need to include some formatting

or

int z = (int) (0.7 * 15000.0);
cout<<"z = "<<z<<endl;
0

精彩评论

暂无评论...
验证码 换一张
取 消