Get rid of error while using relational operator(==) to compare floating variables in c++

Правка en2, от Aman__Raj__, 2020-05-17 19:19:50

Sometimes many of you might encountered an error while checking for equality relation among floating variables.

Let me give you demo with a sample code:-

Here is the code with wrong output:

#include<bits/stdc++.h>
      using namespace std;
       int main()
        {
         double a= ((1.4)*(5))/3;
        double b=7/(3.0);
       if(a==b)
        cout<<"Equal";
       else
     cout<<"Unequal";
      }

**OUTPUT:**
   Unequal

-------------------------------- Process exited after 0.02159 seconds with return value 0

Here is the code that works fine:-

#include<bits/stdc++.h>
      using namespace std;
       int main()
        {
         double a= ((1.4)*(5))/3;
         double b=7/(3.0);
       if(abs(a-b) < 1e-9)
        cout<<"Equal";
       else
        cout<<"Unequal";
      }

 **OUTPUT:**
    Equal

-------------------------------- Process exited after 0.1636 seconds with return value 0

Hope it works! Thanks..

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en2 Английский Aman__Raj__ 2020-05-17 19:19:50 36 Tiny change: 's fine:-\n\n #' -> 's fine:-\n----------------------------------\n\n #'
en1 Английский Aman__Raj__ 2020-05-17 19:17:12 1177 Initial revision (published)