0

I want to write a c++ program that finds whether the triangle is valid or not
here's my code:

#include <iostream>
using namespace std;
int main () {
    int a,b,c;
    cin>>a>>b>>c;
    if (a+b+c==180)
    cout <<"Yes";
    else
    cout <<"No";
    return 0;
}

The user will enter 3 angles e.g 50 30 100 it will print valid Yes, but what if he enters
0 0 180 it will print yes by entering only one angle. that isn't triangle and my program will print yes. What should I do to fix this?

Adam Eve
  • 9
  • 4

2 Answers2

1

In a sense, you are right; there is no point in continuing the program if you have enough information to determine that the triangle is invalid. So, in the code snippet I propose below, you can see that once the user enters a value < 0 or > 180, the program terminates with a suitable error message. Similarly, once the running sum exceeds 180, the program also terminates early.

Finally once all three values are input for the angles, all of which independently are valid angles of a triangle, their sum is checked.

int main() 
{
    // assuming angles must be integers:
    int angle, sum = 0;
    for (int i = 0; i < 3; i++) {
        cin >> angle;
        if (angle <= 0 || angle >= 180) {
            cout << "Error: Angle must be between 0 and 180\n";
            return 0;
        }

        sum += angle;

        if (sum > 180) {
            cout << "Error: angles too large\n";
            return 0;
        }
    }

    if (sum == 180) {
        cout << "Valid Triangle!\n";
    } else {
        cout << "Error: angles must add up to 180\n";
    }
    return 0;
}
Nasser Al-Shawwa
  • 3,573
  • 17
  • 27
0

There are two issues that you have to think about in this code. First: are the angles that the user typed in valid (i.e., not negative, not more than 180 degrees, and maybe not 0). Second, once you have decided that the angles are valid, determine whether the three angles can be part of a triangle.

So write two functions: one that gets an angle by prompting for input, checking that the angle is valid, and looping back if it isn't; and one that decides whether three valid angles are a triangle. Then fasten them together with some appropriate glue.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • I got it, I wrote if (a+b+c == 180 && a>0 && b>0 &&c>0) else cout <<"No"; – Adam Eve Dec 07 '17 at 13:17
  • @AdamEve — cool! Just a personal style tip: I’d write the tests the other way around, testing the requirements first and then the “real” test: `if (a>0 && b>0 && c>0 && a+b+c==180)`. Yours is correct, but in other contexts the order matters. For example: `int *ip = 0; if (ip && *ip)...` — here, testing the validity of the pointer first prevents dereferencing an invalid pointer. – Pete Becker Dec 07 '17 at 14:19