我正在写一个非常简单的字母评分系统,if语句是最有效的吗?
I'm writing a very simple letter grading system, are if statements the most efficient?
代码示例:
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个如果语句,并且看起来很.. cookie-cutter-ish ..我想?是否有更有效/最佳的写作方式?
我查找了C 的一些示例初学者项目,并找到了这个分级,它说有关开关语句的知识将很有用。我调查了这一点,我的理解是,在这种情况下,开关语句的工作方式与语句相同。
您可以使用功能来计算字母。这样:
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 << "Invalidn";
else if (userScore == 100)
std::cout << "You got a perfect score!n";
else
std::cout << "You scored a(n) " << score(userScore) << ".n";
}
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何将enable-if与模板参数和参数包一起使用
- 无论条件是否为true,if总是在c++中执行
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- if数组上的随机数
- 将按位if条件转换为普通if条件
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 使用if-else将数字转换为单词
- 为什么简单的算术减法在"if"条件下不起作用?
- 以在Qt中的IF语句中设置时间延迟
- Craps游戏问题,忽略if语句