使用开关语句 C++ 检查您的评分

check you grade using switch statements c++

本文关键字:检查 C++ 开关 语句      更新时间:2023-10-16

实际上,我不知道从哪里开始。当我在课堂上进行测验时,我遇到了这个问题,我必须弄清楚用户何时输入一些年龄,结果将显示该数字是老、年轻还是婴儿。我已经知道并且这不适用于"开关语句",并且很难写"案例 0:......案例100:"。因为我用谷歌搜索了这个问题,但只能使用"if/else 语句"。如果有任何示例代码与"开关语句"一起使用,或者只是说继续使用"if/else 语句",请指导我。

亲切的问候

这里的开关语句效果很好。

#include<iostream>
#include<iomanip>
using namespace std;
int main() { 
int age;
cout << "Enter your age: " << endl;
cin >> age;
switch (age) {
case 0:
        cout << "Young" << endl;
    break;
case 20:
        cout << "Middle" << endl;
    break;
case 70:
        cout << "Prime" << endl;
    break;
default:
    cout << "Invalid age" << endl;
}
cout << "Your age is " << age << endl;
 system("pause");
 return 0;
 }

在这里 if/else 语句并且效果很好

#include<iostream>
#include<iomanip>
using namespace std;
int main() { 
int age;
cout << "Enter your age: " << endl;
cin >> age;
if (age >= 50) {
    cout << "Prime" << endl;//
}
else if (age >= 20) {
    cout << "Middle" << endl;//
}
else if (age >= 10) {
    cout << "Young" << endl;//
}
else {
    cout << "Baby" << endl;//
}
 system("pause");
 return 0;
 }

为什么要使用 switch 来表示如果写成if块会更好的东西?

一些编译器允许基于范围的switch作为语言扩展(使用像 case 20...69: 这样的符号,但在我看来这毫无意义,因为您最终得到的只是不可移植的代码。

始终为工作选择正确的工具:您不会把衣服放在洗碗机里吧?

参考资料:https://gcc.gnu.org/onlinedocs/gcc/Case-Ranges.html

参考 c++ 文档:

switch 语句的语法有点奇特。其目的是在众多可能的常量表达式中检查一个值。它类似于连接 if-else 语句,但仅限于常量表达式。

不能对表达式使用通配符语法。在我发现的一段类似的代码中,首先评估用户输入并分配了一个从 a 到 d 的字母。在开关的情况下,该字母给出了特定的输入。

您可以像这样堆叠交换机条件:

#include<iostream>
using namespace std;
void Main()
{
    int age; // User-input
    switch (age)
    {
        case 0:
        default:
            cout << "Invalid age." << endl;
            break;
        case 1:          
        case 2:
        case 3:
        // Continue until last age of "young" is reached.  
    } 
}

但是,你可以看到这将是多么可怕。