输入某年某月某日,判断这一天是这一年的第几天?
本题要求根据公历(格里高利历)规则,计算指定日期在该年中的序数天(Day of Year)。关键在于:
累加前 month - 1 个月的总天数;
加上当月的 day;
若为闰年且月份大于 2 月,则总天数加 1。
闰年判断规则(格里高利历):
能被 400 整除 → 闰年;
或能被 4 整除但不能被 100 整除 → 闰年;
其他情况为平年。
即:
注意:2 月在平年为 28 天,闰年为 29 天。因此只有当 月份 > 2 时,闰年才影响“第几天”的计算。
请输入年 月 日:
2024 3 5
是该年的第65天验证:
2024 是闰年(2024 ÷ 4 = 506,且不被 100 整除);
1 月:31 天,2 月:29 天 → 前两月共 60 天;
3 月 5 日 → 60 + 5 = 65
再如:
输入:2023 3 5
输出:第64天(2023 平年,2 月仅 28 天)每月天数固定(除 2 月):
31 天:1, 3, 5, 7, 8, 10, 12 月;
30 天:4, 6, 9, 11 月;
2 月:28 或 29 天(由闰年决定)。
若为闰年且 month > 2,则结果加 1。
import java.util.Scanner;
public class Demo14 {
public static void main(String[] args) {
System.out.println("请输入年 月 日:");
Scanner in = new Scanner(System.in);
int year = in.nextInt();
int month = in.nextInt();
int day = in.nextInt();
System.out.println("是该年的第" + count(year, month, day) + "天");
}
public static int count(int year, int month, int day) {
int sum = 0;
// 累加前 month-1 个月的天数
for (int i = 1; i < month; i++) {
switch (i) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
sum += 31;
break;
case 4: case 6: case 9: case 11:
sum += 30;
break;
case 2:
if (year % 400 == 0 || (year % 4 == 0 && year % 100 != 0)) {
sum += 29;
} else {
sum += 28;
}
break;
}
}
sum += day; // 加上当月天数
return sum;
}
}