完整代码(C语言)
c
#include <stdio.h>
int main() {
int year, month, day;
int days = 0; // 累计天数
// 输入年月日
printf("请输入日期(年 月 日):");
scanf("%d %d %d", &year, &month, &day);
// switch 累加前面月份的总天数
switch (month - 1) {
case 11: days += 30; // 11月
case 10: days += 31; // 10月
case 9: days += 30; // 9月
case 8: days += 31; // 8月
case 7: days += 31; // 7月
case 6: days += 30; // 6月
case 5: days += 31; // 5月
case 4: days += 30; // 4月
case 3: days += 31; // 3月
case 2: days += 28; // 2月(默认28天)
case 1: days += 31; // 1月
case 0: days += day; // 加上当月的天数
}
// 判断闰年:2月多加1天
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
if (month > 2) {
days++;
}
}
printf("这是 %d 年的第 %d 天\n", year, days);
return 0;
}
核心原理
-
switch 没有 break
从
month-1开始一路往下执行 ,把前面所有月份的天数全部累加。 -
天数规则
- 1、3、5、7、8、10、12月:31天
- 4、6、9、11月:30天
- 2月:平年28天,闰年29天
-
闰年判断
满足:
- 能被4整除但不能被100整除 或
- 能被400整除
如果月份大于2,总天数+1。
运行示例
输入:
2025 3 15
输出:
这是 2025 年的第 74 天