过去一个半小时我一直在研究整数的开关,我知道如何使用 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/