Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a simple question about casting integers in c++

Tags:

c++

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

like image 540
Matan Avatar asked Dec 06 '10 12:12

Matan


1 Answers

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.

like image 118
ruslik Avatar answered Sep 20 '22 17:09

ruslik