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

时间:2017-04-29 02:39:44

标签: c++ visual-studio if-statement switch-statement

代码示例:

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语句,看起来非常.. cookie-cutter-ish ..我猜?有没有更有效/最佳的方式来写这个?

我查找了一些C ++的初学者项目示例,并找到this grading one,并且它说switch语句的知识会很有用。我调查了一下,我的理解是,在这种情况下,switch语句的工作方式与if语句的工作方式相同。

1 个答案:

答案 0 :(得分:2)

您可以使用函数计算字母。像这样:

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