Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Andrzejek on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

PROGRAM DOES NOT SEEM TO RECOGNIZE EQUALITY OPERATOR!PLEASE HELP

Status
Not open for further replies.

ankoump

Programmer
May 29, 2002
11
DE
I have written an if statement which states that when x == y a task should be carried out.
Now my values are in double and are decimal values the output is that x = 1.51675 and y= 1.51675 so they are the same. but when the statement is not executed and when i subtract y from x just to test the output is very strange its like 2.356exp-09

How can i stop this?
 
post your exact code snippet so we can look for the problem

[ponytails2]
 
Hi ankoump,
i tried like this, but it is working fine
#include <iostream.h>
#include <iomanip.h>

void main(void)
{
double x=0.0, y=0.0;
x = 1.51675;
y = 1.51675;

if( (x-y) == 0)
cout<<&quot;Equal&quot;<<endl;
else
cout<<&quot;Not Equal&quot;<<endl;
}

try to use also setprecision() or precision()

can i have the complete code??.
 
Never ever compare 2 floating point values for equality without allowing a little difference (like 0.00001).
/JOlesen
 
As was mentioned, never test floating point values for equality. What you can do is replace as follows:
float err = .001;/*or whatever margin of error is valid for you*/
float x = 1.51675, y= 1.51675;

if ( abs((x - y) < err) ) cout << &quot;Equal&quot;;
if ((x - y) < -err ) cout << &quot;Y > X&quot;;
if ((x - y) > err ) cout << &quot;X > Y&quot;;

And of course the same can be done with <=, >= also.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top