Can someone tell me why this simple cose doesn't run right?

It runs just not correctly for some reason

if ( Sum == 180 )
{cout << "This is a triangle!" << endl;
cout << " " << endl;
}
else
{ cout << "This is not a triangle!" << endl;

cout << " " << endl;
}

Heres the math that sum is getting.

( Angle1 ) * 57.2958 + ( Angle2 ) * 57.2958 + ( Angle3 ) * 57.2958

The angles are calculated by user input and converted in the above equation from radians to degrees. This test tells the user if the sum of the angles is even possible to make a triangle. some reason it doesnt work like i want it to. if you need more info I can give more.
Floating point math is not precise. Rounding errors are causing the sum to not add up correctly, so instead of 180, it is 180.0001, which does not equal 180. You would need to make a function that tests if 2 floating point numbers are within a certain distance of each other (think 0.0001), and if they are, then assume them to be equal.
What if I changed the test to be somthin like

if ( Sum > 180 || Sum < 181 )

This should essentially fix my rounding issue but I still end up with the same result. I'm not sure how to make a function that test 2 floating points so maybe you could give me a few more details.
How close do you want the numbers to be before you consider them to be the same number?

if ( Sum > 179.99 && Sum < 180.01 )

Is that close enough? If not, how about

if ( Sum > 179.9999 && Sum < 180.0001 )

Essentially, you must decide how close the numbers have to be to be considered the smae number and then see if the difference of the two numbers is smaller than that amount.

1
2
3
4
5
float maximumDifferenceAllowedToBeConsideredSame = 0.00001;
if (fabs(sum - 180.0) < maximumDifferenceAllowedToBeConsideredSame))
{  cout << "This is a triangle!" << endl;
    cout << " " << endl;
} 

Last edited on
Topic archived. No new replies allowed.