我正在写一个非常简单的字母评分系统,if语句是最有效的吗?

I'm writing a very simple letter grading system, are if statements the most efficient?

本文关键字:if 分系统 语句 有效 简单 非常 一个      更新时间:2023-10-16

代码示例:

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";     
}