是的,除了 -1、0 或 1 之外的任何数字都可能是幻数。
除非您是真正的大师,否则您可能也可以自由使用二的幂:-)
顺便说一句,您可能可以将该代码重构为更容易理解,例如:
string CalcGrade (int s1, int s2, int s3, double median) {
// Grade lookup arrays. If grade is >= limit[n], string is grades[n].
// Anything below D- is a fail.
static const int Limits[] = {400, 380, 360, 340,320, 300, 280,260, 240, 220,200,180 };
static const int Grades[] = {"A+","A","A-","B+","B","B-","C+","C","C-","D+","D","D-"};
double finalGrade = s1 + s2 + s3 + median;
// Check each element of the array and, if the final grade is greater
// than or equal to, return the grade string.
for (int i = 0; i < sizeof(Limits) / sizeof(*Limits); i++)
if (finalGrade >= Limits[i])
return Grades[i];
// Otherwise, failed.
return "Fail";
}
这消除了遍布代码中的神奇数字,使它们的工作原理一目了然(假设您很好地对齐了它们)。
它还消除了您最初的解决方案中的一个问题,即我们如何处理得分为 380.5 的人 - 这不是really让这些机构不及格是公平的:-) 或者给他们打分""
对于 400 以上的人(因为似乎没有办法返回"A+"
).