问:如何使用开关通过角度知道三角形是否有效

Q: How to know whether the triangle is valid or not by angles using switch?

本文关键字:三角形 有效 是否 何使用 开关      更新时间:2023-10-16

我想使用开关,我不能!!

#include <iostream>
using namespace std; 
int main() {
    char op ;
    float x, y, z;
    cout << "Enter the three angles : n "; 
    cin >> x >> y >> z;
    switch (op){
    case '+' :
        cout << x + y + z == 180;
        break;
    default:
        cout << "A triangle is Not valid !! n ";
    }
    system("pause");
}
您可以使用

switch来替代if,如下所示:

#include <math.h>
switch(static_cast<int>(round(x + y + z))) {
case 180:
    cout << "The triangle is validn";
    break;
default:
    cout << "The triangle is not validn";
    break;
}

我使用round()来缓解浮点数学是近似的问题。

如果作业是根据结果进行切换,Baramr 的方法就是你想要的。

为了完整起见:如果作业是根据 op 进行切换以学习跌倒,您可能会在条件中使用中断并跌入默认值,或者如果您有多个操作,请转到标签。

失败和显式跳转都被认为是不好的做法,但是当你学习 switch 时,你应该知道它们至少存在以调试它们。

switch (op){
case '+' :
    if( (static_cast<int>(round(x + y + z))) == 180 ){
        cout << "The triangle is validn";
        break;
    }
default:
    cout << "A triangle is Not valid !! n ";
}

奖励验证:检查角度值是否为负值。

#include <iostream>
#include <cmath>
using namespace std; 
int main() {
    float x, y, z;
    cout << "Enter the three angles : n "; 
    cin >> x >> y >> z;
    if (x <= 0 || y <= 0 || z <= 0) {
        cout << "Invalid angles" << endl;
        system("pause");
        return 0;
    }
    switch (static_cast<int>(round(x + y + z))){
        case 180:
            cout << "Valid triangle" << endl;;
            break;
        default:
            cout << "A triangle is Not valid !! n ";
    }
    system("pause");
}