c++ - C++中的switch语句

标签 c++ switch-statement conditional-statements

考虑:

#include <iostream>

using namespace std;

int main()
{
    int score;
    char grade;
    cout << "Enter your score: " << endl;
    cin >> score;
    if (score >= 90)
        grade = 'a';
    if (score >= 80)
        grade = 'b';
    if (score >= 70)
        grade = 'c';
    if (score >= 60)
        grade = 'd';
    else
        grade = 'f';

    cout << grade << endl;

    switch (grade) {
        case 'a':
            cout << "Good job" << endl;
            break;
        case 'c':
            cout << "Fair job" << endl;
            break;
        case 'f':
            cout << "Failure" << endl;
            break;
        default:
            cout << "invalid" << endl;
    }

    cin.get();
    return 0;
}

为什么当我输入 95 时却给出默认的 switch case,而我应该得到 case 'a'?

最佳答案

您遗漏了一堆 else,或者以错误的顺序进行比较。

95 大于 90,但也大于 80、70 和 60。所以你会得到一个“d”。

(并且您没有在 switch 中处理“d”。)

关于c++ - C++中的switch语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7588364/

相关文章:

C++ 主/工

c++ - 双向链表插入问题

java - 处理:在 for 循环的 if 条件中使用全局数组时出现问题

python - 如何在 Python 中使用 IF ALL 语句

php - value attr CGridView Yii 中的条件语句

c++ - Qt。对 '_time32' 的 undefined reference

c++ - 我的内存没有被释放

java - HashMap vs Switch 语句性能

c++ - 基于传递的 int 的运算符重载?

C# 的 switch 语句区分大小写。有没有办法切换它以使其不区分大小写?