输入为1983,-1 1983,1的时候输出不对,应该是Input year,month:Input year,month:The number of days is 31
时间: 2024-03-03 17:52:00 浏览: 13
确实,输入为1983,-1或1983,1时,程序输出的信息不符合要求。这是因为代码中只对月份的输入进行了合法性判断,而对于年份的输入却没有进行判断,导致了程序在输入年份为负数或0时出现了错误。
为了解决这个问题,我们可以在输入年份之后,先进行年份的合法性判断。具体地,判断年份是否小于1,如果小于1,则输出错误信息并结束程序。改进后的代码如下所示:
```
#include <stdio.h>
int main() {
int year, month, days;
printf("Input year,month:");
scanf("%d,%d", &year, &month);
if (year < 1 || month < 1 || month > 12) { // 判断年份和月份是否合法
printf("Input error\n");
return 0;
}
if (month == 2) { // 判断二月份天数
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
days = 29;
} else {
days = 28;
}
} else if (month == 4 || month == 6 || month == 9 || month == 11) { // 判断30天的月份
days = 30;
} else { // 判断31天的月份
days = 31;
}
printf("The number of days is %d\n", days);
return 0;
}
```
这样,无论输入的年份是多少,程序都能正确地输出结果了。