我有一系列IF语句,我想在switch语句中进行转换,但是我无法成功地在switch的case constant1字段中插入求值。
我知道开关是这样工作的:
switch ( expression ) { //in my case: switch (score) {
case constant1:
statement
break;
case constant2:
statement
default:
statement
break;现在,我尝试将<= 60放在constant1字段中,但当然不起作用。
这是我想要在Switch中转换的一系列IF语句。
if (score <= 60) {
printf("F");
}
if (score <= 70 && score > 60) {
printf("D");
}
if (score <= 80 && score > 70) {
printf("C");
}
if (score <= 90 && score > 80) {
printf("B");
}
if (score <= 100 && score > 90) {
printf("A");
}感谢所有人!
发布于 2017-03-17 16:42:10
switch语句接受常量,而不是条件。例如,你不能说>= const,所以你需要改变策略。
例如,在您的示例中,您可以在两位数分数的第一位数字上进行切换,然后从其中减去1:
switch ((score-1) / 10) {
case 0:
case 1:
case 2:
case 3:
case 4:
case 5: printf("F"); break;
case 6: printf("D"); break;
case 7: printf("C"); break;
case 8: printf("B"); break;
case 9: printf("A"); break;
}情况0..4对switch语句使用C的直通机制,都打印"D"。
上面的代码假设您已经检查了分数的范围为1..100 。
发布于 2017-03-17 16:39:43
正如注释中提到的,你不能这样做,因为在switch语句中,你只能有1表达式。
使用if-else语句,如下所示:
if (score <= 60) {
printf("F");
} else if (score <= 70) {
printf("D");
} else if (score <= 80) {
printf("C");
}
//More statements通过启用交换机的GCC扩展,您可以像这样使用:
switch (score) {
case 0...60:
break;
case 61...70:
break;
//..More cases with range
}发布于 2017-03-17 16:40:15
switch只检查是否相等。因此,在您的示例中,if-else构造更适合。
不过,如果你想使用switch语句,你必须这样做:
switch (score)
{
case 0:
case 1:
case 2:
... // all cases up to 58
case 59:
case 60:
printf("F");
break;
case 61:
...
}不是很漂亮,也不是很乏味。
https://stackoverflow.com/questions/42852663
复制相似问题