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 345
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.
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;
}
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.
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 :(