c语言switch case后加区间
时间: 2023-11-22 13:51:04 浏览: 122
根据提供的引用内容,C语言的switch case语句是不能直接加区间的。但是可以通过一些技巧来实现类似区间的效果。具体方法如下:
1.使用多个case语句来代替区间,例如:
```c
switch (score) {
case 90 ... 100:
printf("优秀\n");
break;
case 80 ... 89:
printf("良好\n");
break;
case 70 ... 79:
printf("中等\n");
break;
case 60 ... 69:
printf("及格\n");
break;
case 0 ... 59:
printf("不及格\n");
break;
default:
printf("输入错误\n");
break;
}
```
2.使用if语句来代替区间,例如:
```c
if (score >= 90 && score <= 100) {
printf("优秀\n");
} else if (score >= 80 && score <= 89) {
printf("良好\n");
} else if (score >= 70 && score <= 79) {
printf("中等\n");
} else if (score >= 60 && score <= 69) {
printf("及格\n");
} else if (score >= 0 && score <= 59) {
printf("不及格\n");
} else {
printf("输入错误\n");
}
```
3.使用函数来代替区间,例如:
```c
int isInRange(int value, int min, int max) {
return value >= min && value <= max;
}
switch (score) {
case isInRange(score, 90, 100):
printf("优秀\n");
break;
case isInRange(score, 80, 89):
printf("良好\n");
break;
case isInRange(score, 70, 79):
printf("中等\n");
break;
case isInRange(score, 60, 69):
printf("及格\n");
break;
case isInRange(score, 0, 59):
printf("不及格\n");
break;
default:
printf("输入错误\n");
break;
}
```
阅读全文
相关推荐


















