I am trying to check if 3 sides form a triangle in C++, but the answer for all possible numbers I tried it says wrong...
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a, b, c;
cin >> a >> b >> c;
if (pow(a,2) == pow(b,2) * pow(c,2) || pow(b,2) == pow(a,2) * pow(c,2) || pow(c,2) == pow(a,2) * pow(b,2))
cout << "The sides form a triangle" << endl;
else
cout << "The sides do not form a triangle." << endl;
return 0;
}
An efficient approach will be to sort the given sides. This will be efficient if you are given an entire array and you are asked whether the given array elements form a triangle or not. This can be applied for n number of given sides. However, this can also be applied for 3 sides. Suppose the given array is b. In your case array b is of length h=3.
Let's say that a, b, c is the sides of the triangle. Therefore, it must be satisfy this criteria :
All the criteria must be true. If one of them are false, then a, b, c will not create the triangle.
Triangle conditions to check for,
Assuming you are only testing for right angled triangles then the logic to use is z^2 = x^2 + y+2 So there's a mistake in the logic:
This should be:
But even with this change the result might be might wrong due to testing equality on floating point numbers. Make a specific function to test 2 floating point numbers are close enough given some tolerance you decide on then use that for comparisons.
If you do not want to limit your approach to only right angled triangles then you might wish to read up on the triangle inequality. In summary the triangle inequality just states that the length of any edge in a triangle must be smaller than the sum of the other 2 edges.
For a normal triangle
For a right angled triangle
Hint:
Actually, given any three sides, you only need to check one condition: that the longest side, say c, is less than the sum of the two shorter sides, say a and b. That is,
This is the essence of the triangle inequality theorem. The other conditions will be trivially true when it is a triangle and irrelevant if this one condition is not. The key, of course, will be to sort the three sides to find the longest side by using a simple sorting algorithm. The assumption in the code is that the sides have already been sorted so that c is the longest.