c ++ int switch语句

时间:2014-02-25 23:15:12

标签: 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";

    }

3 个答案:

答案 0 :(得分:3)

你除以10.0,这是一个双倍,这将无法编译。这必须改为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;
}

答案 1 :(得分:1)

你真的应该用'if'而不是'switch'来做到这一点。类似下面的代码(未测试):

if (testScore >=0 && testScore <= 100)
{
    char grade;

    if (testScore >= 90)
        grade = 'A';
    else if (testScore >= 80)
        grade = 'B';
    else if (testScore >= 70)
        grade = 'C';
    else if (testScore >= 60)
        grade = 'D';
    else
        grade = 'F';

    cout << "Your grade is " << grade << endl;
}
else
{
    cout << "Score of " << testScore << " is not valid" << endl;
}

答案 2 :(得分:0)

我决定这样做,谢谢你的所有答案

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

if (testScore >= 0 && testScore <=100)
{

        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;
        default: 
                cout << "Your grade is F.\n";

        }

}

else 
    cout <<"That score isn't valid" << endl;