题目:编写一个C语言程序,根据输入的月份,输出对应的季节。要求:分别使用if语句、switch语句实现。
时间: 2024-09-27 16:06:50 浏览: 62
c语言if语句实例_C语言if语句和switch语句实例_If..._
当然可以。首先,让我们通过if语句实现这个功能:
```c
#include <stdio.h>
int main() {
int month;
printf("请输入月份(1-12): ");
scanf("%d", &month);
if (month == 1 || month == 2 || month == 12) {
printf("季节是冬季\n");
} else if (month == 3 || month == 4 || month == 5) {
printf("季节是春季\n");
} else if (month == 6 || month == 7 || month == 8) {
printf("季节是夏季\n");
} else if (month == 9 || month == 10 || month == 11) {
printf("季节是秋季\n");
} else {
printf("输入的月份无效\n");
}
return 0;
}
```
接下来,我们可以使用switch语句来达到同样的目的:
```c
#include <stdio.h>
int main() {
int month;
printf("请输入月份(1-12): ");
scanf("%d", &month);
switch (month) {
case 1:
case 2:
case 12:
printf("季节是冬季\n");
break;
case 3:
case 4:
case 5:
printf("季节是春季\n");
break;
case 6:
case 7:
case 8:
printf("季节是夏季\n");
break;
case 9:
case 10:
case 11:
printf("季节是秋季\n");
break;
default:
printf("输入的月份无效\n");
}
return 0;
}
```
阅读全文