+ 2
Can anyone explain this code to me ... Why the output is false?
4 ответов
+ 5
Because floating points are not very accurate.
0.1 is actually 0.10000000000055...
0.2 is 0.20000000000011...
0.3 is 0.29999999999999...
0.1 + 0.2 = 0.30000000000066...
By adding a and b you only accumulate that slight error difference into a bigger error.
Also those digits are made up, I don't know them to the decimal, but they are close enough.
+ 3
That's why you typically don't test for equality of floating point numbers but for
|(a+b) - c| < eps
for some value of eps around 10^-5 instead.
(|x| means the absolute value of x)
+ 1
As you may have seen in the C++ tutorial, double data type (8 bytes) are bigger than a float data type (which is 4 bytes).
Anyway, if you change the data type of all the variables to float, the output will be true.