Friday, July 31, 2009

Why won't y cout if the the "if" statement is true?

c++


using dev-c++


using the following





#include %26lt;iostream.h%26gt;


int main()


{


double x,y;


x=53.26;


y= (x/2) - (.20/2);


if( y == 26.53 )


{


cout %26lt;%26lt; y %26lt;%26lt;endl;


}


return 0;


}





when i do the equation manually y does in fact equal 26.53 but it seems it is not true in the "if" statement. why?

Why won't y cout if the the "if" statement is true?
I think Haley had the best approach here, but not quite there. Somehow i think this is linked as to how the variables are declared.





x=53.26d;


y=(x/2d) - (.20d/2d);





if (y == 26.53){


cout %26lt;%26lt; y %26lt;%26lt; "\n";


}








Try that and see if it works, I haven't compiled it myself. One good debug statement would be adding a


cout %26lt;%26lt; y %26lt;%26lt; endl;


after you set the value for y. It should give you a good idea of what is happening.
Reply:I bet it thinks Y is = to x/2, put ()'s around the entire equations like so....


y= ((x/2)-(.20/2));





HTH!
Reply:Could be rounding error, maybe? I think .1 is one of the numbers computers have a hard time representing and .20/.2 should come out to .1.
Reply:#include %26lt;iostream%26gt;


using namespace std;


int main()


{


double x,y;


x=53.26;


y= ((x/2) - (.20/2));


if( y == 26.529999999999998 )


{


cout %26lt;%26lt; y %26lt;%26lt;endl;


}


system("PAUSE");





}


No comments:

Post a Comment