输入月份判断天数

输入月份判断天数

代码要求

  • 判断闰年
  • 判断大小月
  • 使用switch(我觉得没必要)

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <stdio.h>

int main()
{
int year, month, day;
int big=31, small=30, two29=29, two28=28;
printf("Please Input the Date:");
scanf("%d-%d", &year, &month);
switch (month) {
case 1:
printf("%d days", big);
break;
case 2:
printf("%d days", (year%4==0&&year%100!=0) || year%400==0 ? two29 : two28);
break;
case 3:
printf("%d days", big);
break;
case 4:
printf("%d days", small);
break;
case 5:
printf("%d days", big);
break;
case 6:
printf("%d days", small);
break;
case 7:
printf("%d days", big);
break;
case 8:
printf("%d days", big);
break;
case 9:
printf("%d days", small);
break;
case 10:
printf("%d days", big);
break;
case 11:
printf("%d days", small);
break;
case 12:
printf("%d days", big);
break;
default:
printf("Input error!\n");
}
return 0;
}

亮点!!!

我第一次使用了三目运算符!!!

见第14行代码:

1
printf("%d days", (year%4==0&&year%100!=0) || year%400==0 ? two29 : two28);

实现判断闰年并同时输出2月的天数

备注

这是我第一反应想写的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>

int main()
{
int year, month, day;
int big = 31, small = 30, two29 = 29, two28 = 28;
printf("Please Input the Date:");
scanf_s("%d-%d", &year, &month);
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
printf("%d days", big);
}
else if (month == 4 || month == 6 || month == 9 || month == 11) {
printf("%d days", small);
}
else if (month == 2) {
if (year % 4 == 0 && year % 100 != 0) {
printf("%d days", two29);
}
else
{
printf("%d days", two28);
}
}
else {
printf("Input error!\n");
}
}

确实。可读性没有用switch那么高.


输入月份判断天数
http://example.com/2025/11/10/输入月份判断天数/
作者
王柏森
发布于
2025年11月10日
许可协议