1
float x, y, z;
    x = 0.1;
    y = 0.2;
    z = 0.3;
    if (x + y == z)
        cout << "True" << endl;
    else
        cout << "False" << endl;

I read a question that says 0.1 + 0.2 == 0.3 -> false, when I changed it into variables. It caused true. Why this happens?

Adam Kevin
  • 11
  • 1
  • @NathanOliver The question was talking about "false". – Adam Kevin Mar 20 '18 at 17:52
  • floats are imprecise, and so directly checking the equivalence of floats is generally a bad idea. If you want to see if the sum of `x` and `y` is within a certain range of `z`, try something like checking if `abs((x+y)-z) < 0.0001` or some other appropriate tolerance value. Preferably find a way to not have to rely on float comparisons, though. – Garrett Gutierrez Mar 20 '18 at 17:55
  • @GarrettGutierrez What's the difference between storing them in float variables and comparing them directly w/o variables? – Adam Kevin Mar 20 '18 at 17:57
  • I see, I get your question now. I genuinely don't know the answer to that. It probably has something to do with the compiler optimization. In my version of Visual Studio it is true in debug and false in release. – Garrett Gutierrez Mar 20 '18 at 18:07
  • 1
    You should generally avoid comparisons with `==` and `!=` for floating point values. Prefer `<=`, `>=`, `<`, `>` or compare for equality in a way that takes a reasonably sized epsilon into account. – Jesper Juhl Mar 20 '18 at 18:37

0 Answers0