In: Computer Science
I need a program which tells me if three individual straight line segments form a plane two-dimensional triangle. All three segments will have positive lengths. For example, the three segments 2.5, 3.4 and 5.3 will form a triangle but 1.7, 2.4 and 7.5 will not. If the user enters a zero value, it will be rejected. But if a negative number is entered, it will be changed to the corresponding positive value. Please keep in mind that the length of the longest segment must be less than the sum of the lengths of the other two segments.
The program will accept the three lengths of the segments using the iostream acceptance and testing syntax. Then, it will use a C++ class and a C++ object of that class to find the longest of the three segments and to test whether the three segments will form a triangle. If the three segments will form a triangle the method of your class will return the Boolean value true to the program’s main. Otherwise, it will return the Boolean value false to the program’s main. Then the program’s main will report the result as a text answer to the user, either “true” or “false” and then terminate.
#include<iostream>
using namespace std;
class Triangle{
private:
float side1,side2,side3;
public:
Triangle(float a, float b, float c){
side1 = a;
side2 = b;
side3 = c;
}
bool isTriangle(){
if(side1 + side2 <= side3 || side2 + side3 <= side1 || side3
+ side1 <= side2){
return false;
}
return true;
}
};
int main(){
float a,b,c;
cout<<"Please enter three sides of triangle(one at a
time)\n";
cin>>a;
while (a==0){
cout<<"Invalid input 0! Please enter again\n";
cin>>a;
}
if(a<0)
a = -a;
cin>>b;
while (b==0){
cout<<"Invalid input 0! Please enter again\n";
cin>>b;
}
if (b<0)
b = -b;
cin>>c;
while (c==0){
cout<<"Invalid input 0! Please enter again\n";
cin>>c;
}
if (c<0)
c = -c;
Triangle triangle(a,b,c);
if(triangle.isTriangle()){
cout<<"true\n";
}
else{
cout<<"false\n";
}
return 0;
}
Output: