Aman__Raj__'s blog

By Aman__Raj__, history, 5 years ago, In English

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..

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it