+ 3

C++ Double Type operators != && <

Hello sololearners . What is the difference between these codes //code 1 int main () { double a (0); while (a != 2) a += 0.1; return 0 } cout << a; //the loop doesn't stop //code2 int main () { double a (0); while (a < 2) a += 0.1; return 0 } cout << a; //the program work correctly and it show 2 So why the first work correctly but the second one doesn't in other term what the difference between != && < for double NOTE : with integers there is no problem

27th May 2018, 4:50 PM
Coder++
Coder++ - avatar
2 Answers
+ 14
not a C++ expert, but in most languages 0.1+0.2 != 0.3. Just Google it and you will find tons of articles that explain it better than I would ever be able to. Here is one: http://floating-point-gui.de/basic/
27th May 2018, 5:54 PM
Nikolay Nachev
Nikolay Nachev - avatar
+ 5
Well, hello there) Thats because it’s always an error when it comes to working with real numbers. Try to run this: double a(0); while (a != 2) { a += 0.1; cout<<(2.0 - a)<<endl; if (a > 3) break; } You’ll se something like this: ... 0.2 0.1 -4.44089e-16 -0.1 -0.2 ... So when ‘a’ must had been equal to 2, it’s just became really close to it, but not exactly equal. Thats just how real numbers work. So be really careful with comparing real numbers. P.S. The common practice for this case is comparing numbers with given accuracy: double eps = 1e-6; double a(0); while (abs(a - 2) > eps) a += 0.1; cout<<a; P.P.S Check out the article mentioned by @Nikolay Nachev to dive into the topic in more detail :)
27th May 2018, 5:50 PM
Ali Zhussupov
Ali Zhussupov - avatar