Reputation: 1695
So i have two functions. one function checks to see if the given sides form a right triangle. The problem is that when I call the function in the if-else statement in classify, I always get "Not a right Triangle" even though the value of isRightTriangle(sides) is true.
bool isRightTriangle(int sides[])
{
std::sort(sides, sides+3);
if((pow(sides[0],2) + pow(sides[1],2)) == pow(sides[2],2))
return true;
return false;
}
void classify(int sides[], ofstream &outfile)
{
int largest(int []);
void typeOfTriangle(int [], ofstream &);
bool isRightTriangle(int []);
outfile << "Largest Side: " << largest(sides) << endl;
typeOfTriangle(sides,outfile);
if(isRightTriangle(sides))
outfile << "Right Triangle\n\n\n";
else
outfile << "Not a Right Triangle\n\n\n";
}
Upvotes: 0
Views: 219
Reputation: 137930
Floating point arithmetic doesn't generally produce perfectly precise results, but ==
checks for exact equality. Instead of comparing a == b
, use abs( a - b ) < precision_limit
. This essentially applies to floating-point arithmetic in all languages.
This doesn't explain why it would fail for 3, 4, 5
, but there appears to be a lot of code you're not showing us. It would be a very good idea to have isRightTriangle
print the numbers it's analyzing before the if
.
(By the way, now I see you're passing integers to pow
. In this case, imprecise results can only occur for very large numbers, and the precision_limit
would be at least one.)
Upvotes: 8
Reputation: 23237
As others have mentioned, you're using floating point values and expecting exact results. Since you're only ever squaring the numbers (pow(x, 2)
) you should just multiply them together instead. That's usually faster than pow, even for floats, and it works for any type of number.
Upvotes: 2