C++ int switch 语句

标签 c++ switch-statement

过去一个半小时我一直在研究整数的开关,我知道如何使用 char 进行开关,但这对我来说似乎很难。任何建议将不胜感激。我遇到的问题是我不能接受此开关当前所做的超过 100 的成绩

    int testScore;                     
    cout <<"Enter your test score and I will tell you \n";
    cout <<"the letter grade you earned ";
    cin >> testScore;

    switch(testScore/10)
{ 
    case 10:
    case 9:
        cout <<"Your grade is A.\n";
    break;
    case 8: 
        cout <<"Your grade is B.\n";
    break;
    case 7: 
        cout <<"Your grade is C.\n";
        break;
    case 6: 
            cout << "Your grade is D.\n";
        break;
    case 5: 
            cout << "Your grade is F.\n";
        break;

    default:
        cout << "That score isn’t valid\n";

    }

最佳答案

您除以 10.0,这是一个 double 值,无法编译。这必须更改为 10。 此外,您应该在 switch 语句之前使用 if 语句来检查它是否在有效范围内。

#include<iostream>
#include<iomanip>
using namespace std;
int main() 
{

int testScore;
cout <<"Enter your test score and I will tell you \n";
cout <<"the letter grade you earned \n";
cin >> testScore;

if (testScore<=100 && testScore>=0)
    switch(testScore/10)
    {
        case 10:
        case 9:
            cout <<"Your grade is A.\n";
            break;
        case 8:
            cout <<"Your grade is B.\n";
            break;
        case 7:
            cout <<"Your grade is C.\n";
            break;
        case 6:
            cout << "Your grade is D.\n";
            break;
        case 5:
            cout << "Your grade is F.\n";
            break;

        default:
            cout << "That score isn’t valid\n";
    }
else
    cout <<"That score isn't valid\n";

return 0;
}

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

相关文章:

c++ - 如何在 OpenGL/GLSL 中对特定颜色进行阈值处理

c++ - 如何在非选定选项卡中的 QTabWidget 中绘制 Qt 小部件?

c# - 在 Enum C# 中使用 Switch 语句

c++ - 如何避免多重定义链接错误?

c++ - C++类中无法重载+运算符

c++ - ferror() 返回值的消息文本

javascript - 在这个 switch 语句中执行 `return ' ' ;` or ` return null;` 是否更有意义?

c - 在此系统中不断出现此错误 "linker command failed with exit code 1"

linux - bash |计算没有 "find"的文件

ruby-on-rails - ruby - 在 case 语句中使用 include 方法