这是我的作业规范的最后一部分,我无法弄清楚:
使用默认情况来捕捉'各种等级。 不要将0到59之间的每个数字列为单独的案例!
这是我的代码,我的默认需要使用上面的说明考虑0到59之间的值。
感谢您提供任何帮助/建议。
double percentage;
int grade;
cout << "Enter your grade percentage " <<endl;
cin >> percentage;
if (percentage < 0 || percentage > 100 )
cout << "Invalid entry " << endl;
grade = (int)round(percentage);
cout << fixed << setprecision(2);
switch(grade)
{
case 100:
case 99:
case 98:
case 97:
case 96:
case 95:
case 94:
case 93:
case 92:
case 91:
case 90:
cout << "Percentage: " << percentage << "% " << "Grade: A " << "Points: 4.00";
break;
case 89:
case 88:
case 87:
case 86:
case 85:
case 84:
case 83:
case 82:
case 81:
case 80:
cout << "Percentage: " << percentage << "% " << "Grade: B " << "Points: 3.00";
break;
case 79:
case 78:
case 77:
case 76:
case 75:
case 74:
case 73:
case 72:
case 71:
case 70:
cout << "Percentage: " << percentage << "% " << "Grade: C " << "Points: 2.00";
break;
case 69:
case 68:
case 67:
case 66:
case 65:
case 64:
case 63:
case 62:
case 61:
case 60:
cout << "Percentage: " << percentage << "% " << "Grade: D " << "Points: 1.00";
break;
default:
cout << "Percentage: " << percentage << "% " << "Grade: F " << "Points: 0.00";
break;
}
return 0;
}
答案 0 :(得分:1)
与@ dvix的评论一致,如果您知道成绩将在0到100之间,则可以通过以下方式缩短代码:
switch( grade/10 ) {
case 10:
case 9:
... Do something ...
break;
case 8:
case 7:
... Do something else...
break
....
}
并在最后使用默认值,节省了几个案例。
话虽如此,if
可能是正常处理这种情况的惯用方式。