My question was:
Write a program that reads three non-zero double values and determines and prints whether they are sides of a right triangle. The program should verify the results up to 4 decimal places. [Hint: Use Pythagoras' theorem to determine whether the three sides form right triangle.]
The sample output is:
Enter length of three sides: 3 4 5
The sides represents right triangle.
Enter length of three sides: 4 5 6.403
The sides don’t represents right triangle.
Enter length of three sides: 4 5 6.4031
The sides represents right triangle.
I used this approach but can't understand how to verify up to 4 decimal places. Please help with this or at least give a hint.
My Code:
#include <iostream>
using namespace std;
int main() {
double s1, s2, s3;
cout<<"Enter length of three sides: ";
cin>>s1>>s2>>s3;
s1 *= s1;
s2 *= s2;
s3 *= s3;
if ((s1 == s2 + s3) || (s2 == s1 + s3) || (s3 == s1 + s2)) {
cout<<"The sides represents right triangle."<<endl;
}
else {
cout<<"The sides don't represents right triangle."<<endl;
}
}
Someone told me use for setprecision, but how?
It is all about rounding and also about the precision of double numbers. Comparison for equality is basically not possible.
As you have read in the comments and as for example shown here, there are ways to somehow compare doubles.
And here your 4th decimal place will help.
Comparison can basically done with the following formula:
And here we can set the epsilon to 0.001, which gives you the desired result.
Do not forget to find the hypotenuse! This is the longest side.
Please see the following example: