+ 1

# I can't understand why not equal

in this code, why (x!=0.3) and (y!=0.6) ? #include <iostream> using namespace std; int main() { float x; double y; x = 0.1+0.1+0.1; y = 0.2+0.2+0.2; if (x==0.3) cout << "true \n"; else cout << "false \n"; if (y==0.6) cout << 1 << endl; else cout << 0 << endl; return 0; }

3 Answers

+ 4

It's related on how float and double are written by the computer. It's first converted to binary and then translated on a power of 2.
As it's stocked on minimum 4 (8 for double) bytes and not an infinity, there is a little difference on the real value and the approximated one (in power of 2). It can accumulate quite quickly with operations.
That's why :
#include <iostream>
using namespace std;
int main() {
cout << 0.3 - 0.1 - 0.1 - 0.1 << endl;
return 0;
}
will output :
-2.7756e-17

+ 1

more info here :
https://en.m.wikipedia.org/wiki/Floating_point

+ 1

Thanks Dorian, I understood it.