题目
读入年份和月份(1~12),输出该月有多少天。
思路
读年份与月份,月份非法直接报错。2 月天数由闰年判定;其余月用数组 {31,28,...} 或 switch 查表,闰年时 2 月为 29。
解题分析
大月 31、小月 30,2 月单独看闰年。闰年规则同第 2 题。月份非法应单独分支,不要访问越界数组。
完整程序
#include <stdio.h>
static int is_leap(int year)
{
return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
}
int main(void)
{
int year, month;
if (scanf("%d %d", &year, &month) != 2) {
return 1;
}
int days;
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
days = 31;
break;
case 4: case 6: case 9: case 11:
days = 30;
break;
case 2:
days = is_leap(year) ? 29 : 28;
break;
default:
printf("无效月份\n");
return 0;
}
printf("%d\n", days);
return 0;
}运行示例
输入:
2024 2输出:
29再试,输入:
2023 2输出:
28其它写法
下面每种写法都是完整程序,输入输出格式与正文一致,便于对照。
月份天数表
程序:
#include <stdio.h>
static int is_leap(int y)
{
return (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0);
}
int main(void)
{
int y, m;
if (scanf("%d %d", &y, &m) != 2) {
return 1;
}
int d[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (m < 1 || m > 12) {
printf("无效月份\n");
return 0;
}
int days = d[m];
if (m == 2 && is_leap(y)) {
days = 29;
}
printf("%d\n", days);
return 0;
}运行示例
输入:
2024 2输出:
29