0

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!!!

Hurley Li
  • 11
  • 4
  • Did you try 64.01? – nicomp Aug 20 '17 at 02:09
  • yes, 64.01 gave expected results for both int and double. anything <64.02 gave expected results... – Hurley Li Aug 20 '17 at 02:10
  • What do you think the results should be and what results are you getting? – nicomp Aug 20 '17 at 02:11
  • I just added expected results in the question. I was hoping to see if anyone can replicate these results. I also run it on a online c++ shell, it gave the same results, so it didn't seem to be due to my machine. – Hurley Li Aug 20 '17 at 02:14

1 Answers1

1

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.

Robinson
  • 9,666
  • 16
  • 71
  • 115
  • aha! that make sense! Sorry it's being pointed out as a duplicate question, I swear I tried to search the answer for a long time. I guess the question I searched is too specific. – Hurley Li Aug 20 '17 at 02:20