I can't understand why not equal | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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; }

22nd Jun 2016, 6:21 PM
Sami
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
22nd Jun 2016, 7:09 PM
Dorian
22nd Jun 2016, 7:13 PM
Dorian
+ 1
Thanks Dorian, I understood it.
22nd Jun 2016, 9:31 PM
Sami