将if语句转换为switch但不起作用,转换哪里出错了



这是代码的一部分,它从文本文件中获取一行数字,并计算每个指定范围中适合的数字数量。我把它从if,else-if语句转换过来(这很好(只是为了练习。但是,除了文本文件中的最高数字1之外,没有任何数字在计数,它符合此开关的默认值。我哪里错了?

int i = 0;
switch (students[i].Grade)
{
case 1:
{
if(students[i].Grade <= 59) 
distributions[0] += 1;
break;
}
case 2:
{
if(students[i].Grade >= 60 && students[i].Grade <= 69)
distributions[1] += 1;
break;
}
case 3:
{
if(students[i].Grade >= 70 && students[i].Grade <= 79)
distributions[2] += 1;
break;
}
case 4:
{
if (students[i].Grade >= 80 && students[i].Grade <= 89)
distributions[3] += 1;
break;
}
// students with grade of 90 or above
default:
{
distributions[4] += 1;
break;
}
}
Console.WriteLine("0-59: {0}n60-69: {1}n70-79: {2}n80-89: {3}n90-100: {4}", distributions[0], distributions[1], distributions[2], distributions[3], distributions[4]);

这是使用if-else-if语句的代码,运行良好。

for (int i = 0; i < students.Length; i++)

if (students[i].Grade <= 59)
{
distributions[0] += 1;
}
else if (students[i].Grade >= 60 && students[i].Grade <= 69)
{
distributions[1] += 1;
}
else if (students[i].Grade >= 70 && students[i].Grade <= 79)
{
distributions[2] += 1;
}
else if (students[i].Grade >= 80 && students[i].Grade <= 89)
{
distributions[3] += 1;
}
//students with grade of 90 or above
else
{
distributions[4] += 1;
}
Console.WriteLine("0-59: {0}n60-69: {1}n70-79: {2}n80-89: {3}n90-100: {4}", distributions[0], distributions[1], distributions[2], distributions[3], distributions[4]);           

如果你使用c#7+,你可以尝试这个

for (int i = 0; i < students.Length; i++) 
switch (students[i].Grade)
{
case int n when (n <=59):
distributions[0] += 1;
break;

case int n when (n >= 60 && n <= 69):
distributions[1] += 1;
break;
.... and so on
}

switch语句将students[i].Grade中的值与单词"后面的每个整数进行比较;案例";。所以情况1:将students[i].Grade1进行比较,但这永远不是真的。234也没有,所以它总是在默认情况下进行。所以这里的切换表达式不是一个好主意,因为你不能在一个"case";

您可以使用一个新的C#9.0模式匹配功能,该功能允许您将模式与andor组合

switch (students[i].Grade) {
case <= 59:
distributions[0] += 1;
break;
case >= 60 and <= 69:
distributions[1] += 1;
break;
case >= 70 and <= 79:
distributions[2] += 1;
break;
case >= 80 and <= 89:
distributions[3] += 1;
break;
default:
distributions[4] += 1;
break;
}

但是你可以稍微简化一下逻辑。例如,你不必测试成绩>=60,因为按顺序评估案例并且案例<=59已经过测试(如果其他解决方案也是如此(

switch (students[i].Grade) {
case < 60:
distributions[0] += 1;
break;
case < 70:
distributions[1] += 1;
break;
case < 80:
distributions[2] += 1;
break;
case < 90:
distributions[3] += 1;
break;
default:
distributions[4] += 1;
break;
}

注意,如果Gradeint,则<= 59等效于< 60。我用了第二个,因为它看起来更好。

使用新的开关表达式(C#8.0(可以实现另一种简化:

int index = students[i].Grade switch {
< 60 => 0,
< 70 => 1,
< 80 => 2,
< 90 => 3,
_ => 4
};
distributions[index] += 1;

最新更新