代码示例:
question:
cout << "Enter the grade % you scored on the test: ";
cin >> userScore;
if (userScore == 100) {
cout << "You got a perfect score!" << endl;
}
else if (userScore >= 90 && userScore < 100) {
cout << "You scored an A." << endl;
}
else if (userScore >= 80 && userScore < 89) {
cout << "You scored a B." << endl;
}
//... and so on...
else if (userScore >= 0 && userScore < 59) {
cout << "You scored an F." << endl;
}
goto question;
这段代码总共有 6 个 if 语句,它看起来非常..千篇一律..我猜?有没有更有效/最佳的方式来写这个?
我查了一些 C++ 的示例初学者项目,发现这个评分为 one,它说 switch 语句的知识会很有用。我研究了一下,我的理解是,在这种情况下,switch 语句的工作方式与 if 语句相同。
您可以使用函数来计算字母。像这样:
char score(int s) {
if (s < 60)
return 'F';
return (9 - s / 10) + 'A';
}
int main(int argc, char **argv){
int userScore;
std::cout << "Enter the grade % you scored on the test: ";
std::cin >> userScore;
if (userScore < 0 || userScore > 100)
std::cout << "Invalid\n";
else if (userScore == 100)
std::cout << "You got a perfect score!\n";
else
std::cout << "You scored a(n) " << score(userScore) << ".\n";
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句