casting - c++ same calculation assigned to int or double gives different results, but only for certain values (is 64.02 a magic number in c++?) -
this question has answer here:
- is floating point math broken? 20 answers
i tried assign calculation result variable, , print out. however, depending on type of variable it's assigned to, results different. unexpected results happened values specific calculation.
int main() { // above 64.02 give unexpected results // e.g. (100.02 - 100.0) * 100.0 int ((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 // 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 question specific, suspect has implicit type cast. why values >=64.02?
this first ever question on stack overflow, please don't -1 me!!!
64.02 representation floating point 64.01999664306640625. after computation 1.999664306640625, 1 when rounded down int.
63.02 representation 63.020000457763671875, gives 2 after computation, when rounded down int.
some numbers cannot stored float or double.
Comments
Post a Comment