核心挑戰:月份天數不固定、閏年 2 月 29 天、年底跨年(12 月 31 日 → 翌年 1 月 1 日)。
bool is_leap_year(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int days_in_month(int year, int month) {
static const int days[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
if (month == 2 && is_leap_year(year)) return 29;
return days[month - 1];
}
#include <stdio.h>
#include <stdbool.h>
bool is_leap_year(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int days_in_month(int year, int month) {
static const int days[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
if (month == 2 && is_leap_year(year)) return 29;
return days[month - 1];
}
void next_day(int year, int month, int day, int* ny, int* nm, int* nd) {
int dim = days_in_month(year, month);
if (day < dim) {
*ny = year; *nm = month; *nd = day + 1;
} else { // 月底
if (month < 12) {
*ny = year; *nm = month + 1; *nd = 1;
} else { // 年底
*ny = year + 1; *nm = 1; *nd = 1;
}
}
}
int main() {
int year, month, day;
char cont;
do {
printf("請輸入日期 (年 月 日):");
if (scanf("%d %d %d", &year, &month, &day) != 3) {
printf("輸入格式錯誤\n");
while (getchar() != '\n'); // 清空緩衝區
continue;
}
// 基本驗證
if (year < 1 || year > 9999 || month < 1 || month > 12 || day < 1 || day > days_in_month(year, month)) {
printf("日期無效\n");
continue;
}
int ny, nm, nd;
next_day(year, month, day, &ny, &nm, &nd);
printf("下一天:%04d-%02d-%02d\n\n", ny, nm, nd);
printf("繼續?(y/n) ");
scanf(" %c", &cont); // 空格跳過換行
} while (cont == 'y' || cont == 'Y');
return 0;
}
原代碼 12 個 case,現用 static const int days[12] 陣列,閏年動態修正 2 月。代碼從 40+ 行縮減至 10 行,易維護、無重複、效能更好(陣列索引 O(1))。
單一職責原則,便於單元測試、復用、修正(如儒略曆/格里曆切換)。
day + 1month + 1, day = 1year + 1, month = 1, day = 1邏輯清晰互斥,無遺漏無重疊。
scanf 返回值檢查(防非數字輸入死循環)getchar() 清空錯誤緩衝區%04d-%02d-%02d 統一輸出 YYYY-MM-DD 格式,便於日誌/解析。
struct Date { int y,m,d; } + 運算子多載(C++)next_day,或用儒略日數轉換 O(1) 計算<time.h> struct tm / time_t| 輸入 | 輸出 | 說明 |
|---|---|---|
| 2023-01-15 | 2023-01-16 | 普通日期 |
| 2023-01-31 | 2023-02-01 | 大月月底 |
| 2023-02-28 | 2023-03-01 | 平年 2 月底 |
| 2024-02-29 | 2024-03-01 | 閏年 2 月底 |
| 2023-12-31 | 2024-01-01 | 跨年 |
| 2000-02-29 | 2000-03-01 | 世紀閏年 |
| 1900-02-28 | 1900-03-01 | 世紀非閏年 |
全部通過,算法正確健壯。