Right Triangle calculation program question

I'm creating a right triangle calculation program to determine whether or not the user input of 3 sides of a triangle equals out to a right triangle or not. For the most part the program does work.

Example: Input of 3 4 5

This is the output from the program, it works.

Please enter three sides of a triangle: 3 4 5
This is a right triangle.

legC = 25
legA + legB = 25
Press any key to continue . . .


However please note that a problem occurs when entering decimal form. I'm trying to figure out what the problem is.

Example: Input of .48 .64 .8
This is the output from the program, it fails logically.

Please enter three sides of a triangle: .48 .64 .8
This is NOT a right triangle.

legC = 0.64
legA + legB = 0.64
Press any key to continue . . .


I'm still a beginner so i'm not 100% sure I know what i'm doing. The program works it just bugs logically due to the decimal form. 0.64 is == 0.64
So my code if (legC == pow(legA, 2.0) + pow(legB, 2.0)) is failing some how.

Source Code
--------------------------------------------------------------------------------
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
double legA;
double legB;
double legC;

cout << "Please enter three sides of a triangle: ";
cin >> legA; cin >> legB; cin >> legC;

legC = pow(legC, 2.0);

if (legC == pow(legA, 2.0) + pow(legB, 2.0))
{
cout << "This is a right triangle. " << endl;
cout << endl;
}
else
{
cout << "This is NOT a right triangle. " << endl;
cout << endl;
}

// Testing Results
cout << "legC = " << legC << endl;
cout << "legA + legB = " << pow(legA, 2.0) + pow(legB, 2.0) << endl;

return 0;
}
--------------------------------------------------------------------------------
Same thing applies, I'm currently still just working on the main() function, I do not know classes etc, just simple straight forward programs thus far.

Any ideas would be appreciated, thanks much.

-Matorian
1) pow() is overkill for squaring things. x*x is preferable to pow(x,2.0).

2) you can't do direct == or != comparisons with floating points because floating points are approximations.

Read this for more info: http://www.parashift.com/c++-faq-lite/newbie.html#faq-29.17
2) you can't do direct == or != comparisons with floating points because floating points are approximations.


The solution I could think of is to ask the business user to which decimal point do they "consider" two floating point values are equal. They may say round up to 2 decimal places. Then I write a class and overload the ==, != etc operators and implement the business user defined logic.

Above is a classic case where operator overloading for C++ comes in very handy for which Java don't give me :(
Topic archived. No new replies allowed.