Блог пользователя Aman__Raj__

Автор Aman__Raj__, история, 4 года назад, По-английски

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

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится