Hurley Li - 1 month ago 15

C++ Question

I tried to assign a calculation result to a variable, and print it out. However, depending on the type of the variable it's assigned to, the results are different. But the unexpected results only happened for certain values for this specific calculation.

`int main() {`

// anything above 64.02 give unexpected results

// e.g. (100.02 - 100.0) * 100.0

int a ((64.02 - 64.0) * 100.0);

double b ((64.02 - 64.0) * 100.0);

cout<<"result: "<<a<<endl; // result: 1, expected result: 2

cout<<"result: "<<b<<endl; // result: 2, expected result: 2

// anything below 64.02 give right results

int c ((63.02 - 63.0) * 100.0);

double d ((63.02 - 63.0) * 100.0);

cout<<"result: "<<c<<endl; // result: 2, expected result: 2

cout<<"result: "<<d<<endl; // result: 2, expected result: 2

return 0;

}

I know this question is very specific, but I suspect it has something to do with implicit type cast. But why only for values >=64.02?

This is my first ever question on stack overflow, please don't -1 me!!!

Answer Source

64.02 representation as a floating point is actually 64.01999664306640625. After the computation you get 1.999664306640625, which is 1 when rounded down to int.

63.02 representation is 63.020000457763671875, which gives you 2 after the computation, when rounded down to int.

Some numbers cannot be stored exactly as float or double.