Why I can not convert float to int correctly

The folloing code looks to me a bug. Can any body help? Thanks

float c= 0.01, v=0.001;
float u= c/v;
cout<< "u="<<u<<endl;
int y =(int) u;
cout<< " y=" <<y<< endl;

/// Output

u=10
y=9
Last edited on
This is due to the inaccuracies of floating point. The division is probably getting something like 9.9999988..., and that would display as 10 as a float but it would be truncated when converted to an int.
You are right. I chenged the type from flopat to double and I got correct answer. Thanks

Double c= 0.01, v=0.001;
double u= c/v;
cout<< "u="<<u<<endl;
int y =(int) u;
cout<< " y=" <<y<< endl;

/// Output

u=10
y=10
@MatrixZ
mark it as solved, so that other people, which will try to help, won't get in, while people looking for an answer will know the answer is available.
double is innaccurate too. You may want to round instead of truncate.
Topic archived. No new replies allowed.