出一道c语言条件判断的难题,只用if和switch解答,不用其他语句
时间: 2024-10-05 14:02:09 浏览: 27
这是一个用C语言仅限if和switch完成的挑战题目,目标是判断一个整数属于特定的范围,并执行相应的操作:
```c
#include <stdio.h>
int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
// 使用if-else if-else链路
if (num >= 0 && num <= 5) {
printf("Number is between 0 and 5. Operation A.\n");
} else if (num > 5 && num <= 10) {
printf("Number is between 6 and 10. Operation B.\n");
} else if (num > 10 && num <= 20) {
printf("Number is between 11 and 20. Operation C.\n");
} else if (num > 20) {
printf("Number is greater than 20. Operation D.\n");
} else { // 如果不在上述范围内
printf("Number is less than 0 or not within the given range.\n");
}
// 使用switch-case
switch (num / 5) {
case 0:
printf("Number is a multiple of 5 in range [0-5].\n");
break;
case 1:
printf("Number is either 6, 11 or higher multiples of 5.\n");
break;
default:
printf("Number does not fall into the above categories.\n");
break;
}
return 0;
}
```
在这个例子中,我们首先用if-else if-else检查数字是否在每个区间内,然后用switch-case将数字分成每5的倍数段进行判断。
阅读全文