In: Computer Science
Write an interactive C++·program to determine a type of a triangle based on three sides.
Length of three sides of a triangle.
Length of three sides; type of triangle; whether or not a triangle is a right triangle. Output an appropriate error message for invalid lengths entered for one or more sides or side lengths that cannot form a triangle.
C++ code:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// function to check if the valid triangle can be formed
bool is_valid(int a, int b, int c){
if ( a+b <= c) return false;
if ( b+c <= a) return false;
if ( c+a <= b) return false;
return true;
}
int main() {
// Take input
float a, b, c;
cout << "Enter the three sides of a triangle separated by a space: ";
cin >> a >> b >> c;
// Invalid lengths
if ( a <= 0 || b <= 0 || c <= 0 ){
cout << "Invalid lengths have been entered" << endl;
}
// Invalid triangle
else if (is_valid(a, b, c) == false){
cout << "The given lengths cannot form a triangle" << endl;
}
// Equilateral Triangle
else if ( a == b && b == c){
cout << a << " " << b << " " << c << "; " << "Equilateral Triangle; " << "Not a right triangle" << endl;
}
// Isosceles Triangle
else if ( a == b || b == c || c == a){
if ( pow(a,2) + pow(b,2) == pow(c,2) || pow(b,2) + pow(c,2) == pow(a,2) || pow(c,2) + pow(a,2) == pow(b,2) ){
cout << a << " " << b << " " << c << "; " << "Isosceles Triangle; " << "Is a right triangle" << endl;
}else{
cout << a << " " << b << " " << c << "; " << "Isosceles Triangle; " << "Not a right triangle" << endl;
}
}
// Scalene Triangle
else{
if ( pow(a,2) + pow(b,2) == pow(c,2) || pow(b,2) + pow(c,2) == pow(a,2) || pow(c,2) + pow(a,2) == pow(b,2) ){
cout << a << " " << b << " " << c << "; " << "Scalene Triangle; " << "Is a right triangle" << endl;
}else{
cout << a << " " << b << " " << c << "; " << "Scalene Triangle; " << "Not a right triangle" << endl;
}
}
return 0;
}
Sample execution of the above code: