- 10. Make a program that takes all three sides of a triangle and tells you if it is equilateral, isosceles, or scalene.
C++ Triangle Types
There are three types of triangle:- Equilateral: all sides are equal
- Isosceles: Only Two Sides Are Equal
- Scalene: All Sides Are Different
So all we have to do is ask for three sides of a triangle, and test whether the sides are all the same, or have two equal or if it's all different.
One way to do this is by testing if it's all the same in an IF, to know if it's equilateral:
- if ((a == b) && (b == c))
Then if they are all different, to know if it is scalene:
- if ((a! = b) && (a! = c) && (b! = c))
If it is none of the above, it is because it is isosceles.
Our code looks like this:
#include <iostream> using namespace std; int main() { int a, b, c; cout << "Side a: "; cin >> a; cout << "Side b: "; cin >> b; cout << "Side c: "; cin >> c; if( (a==b) && (b==c) ) cout<<"Equilateral\n"; else if( (a!=b) && (a!=c) && (b!=c)) cout<<"Scalene\n"; else cout<<"Isosceles\n"; }
Equilateral, Isosceles or Scalene?
An interesting thing about programming is that code is a kind of fingerprint.Each one does their own thing, each one has their own methods, lines of thought and creativity.
Sometimes it is common to make big code, ugly and confusing.
Then we see someone using half the lines we use, doing something far more beautiful and comprehensive.
That's why it's important to study through other people's books, websites, tutorials, and codes to 'pick up' on others' reasoning. Never miss this custom, okay?
Let's go for one more solution.
First, let's test if there are two equal sides:
- (a == b) || (a == c) || (b == c)
If you have, either one: either equilateral or just isosceles.
So we test if the three sides are equal:
- (a == b) && (b == c)
If so, we say it is equilateral. Otherwise it falls into the nested ELSE and we say it is isosceles.
If it does not have at least two equal sides, it is scalene.
Look:
#include <iostream> using namespace std; int main() { int a, b, c; cout << "Side a: "; cin >> a; cout << "Side b: "; cin >> b; cout << "Side c: "; cin >> c; if( (a==b) || (a==c) || (b==c)) if( (a==b)&&(b==c) ) cout<<"Equilateral\n"; else cout<<"Isosceles\n"; else cout<<"Scalene\n"; }
C++ hacker test
A hacker is the one who finds loopholes, errors, code problems.
There is a problem with the code above: the conditions of existence of a triangle.
It's not just entering three values and we have a triangle, no.
Research the conditions of existence of a triangle, and before deciding whether it is equilateral, isosceles or scalene, see if the triangle can even exist.
Post your code in the comments.
No comments:
Post a Comment