I have been asked to write a program(in C++) which, given three values representing the sides of a triangle prints:
0 if the values cannot be the sides of any triangle. This is so if any value is negative or zero, or if any length is greater than the sum of the other two.
1 If the triangle is equilateral.
2 If the triangle is isosceles
3 if the triangle is scalene.
**********************HERE IS MY PROGRAM*********************
#include <iostream>
#include <cmath>
usingnamespace std;
int main(){
double a,b,c;
cout<<"enter 3 values of your triangle"<< endl;
cin>>a>>b>>c;
if( (a==b&& a!=c) || (a==c && a!=b) || (b==c && b!=a) ) {
cout<< " This triangle is Isosceles"<<endl;
}
elseif( a==b && a==c){
cout<< "This triangle is equilateral"<<endl;
}
elseif (a!=b && a!=c){
cout<<" This triangle is scalene"<<endl;
}
return 0;
}
I have WRITTEN almost all of the program and it works! however I do not understand how to implement this part: "0 if the values cannot be the sides of any triangle. This is so if any value is negative or zero, or if any length is greater than the sum of the other two." Can someone kindly tell me what does this means?
Check to make sure that non of the values entered are negative or zero. This should be easy enough. If a side has a length of zero or less then it can't possibly form a triangle.
Then check each side to make sure it's length isn't greater than the sum of the other two. Again, if the sum of the other two side is less than the length of one side, they can't logically form a triangle.
1 2
if( c > ( a + b ) )
cout << "Cannot be a triangle\n";
You'll need to add or statements for the other two sides.
/* If a or b or c is less than or equal to 0 then print " cannot be a triangle"
if c is greater than the sum of a and b then print "cannot be a triangle"
*/
if( c > ( a + b ) && a<=0|| b<=0 || c<=0)
cout << "Cannot be a triangle\n";
You cant have negative sides or a side missing (a side with 0 length). Also, you cant have a triangle with sides 100,1, and 5 because 1+5>100, meaning the longest side is stretched out so far, that the other sides cannot connect to it. This results in an open figure. Therefore, you must change your program like this:
#include <iostream>
int main()
{
double a,b,c;
std::cout<<"This program finds out if a triangle is scalene, isosceles, or equilateral."<<std::endl;
std::cout<<"Enter the 3 sides' values of your triangle:"<<std::endl;
std::cout<<"A? ";
std::cin>>a;
std::cout<<"B? ";
std::cin>>b;
std::cout<<"C? ";
std::cin>>c;
if(((a+b)<c)||((a+c)<b)||((b+c)<a))
{
std::cout<<"The sides of this triangle do not match.";
}
elseif ((a<=0)||(b<=0)||(c<=0))
{
std::cout<<"Sides cannot be zero or less than zero.";
}
elseif((a==b&& a!=c)||(a==c && a!=b)||(b==c && b!=a))
{
std::cout<<"The triangle is Isosceles.";
}
elseif( a==b && a==c)
{
std::cout<<"The triangle is equilateral.";
}
else
{
std::cout<<"The triangle is scalene.";
}
return 0;
}