閏年規則
- 能被 4 整除且不能被 100 整除 → 閏年。
- 能被 400 整除 → 閏年。
- 其餘 → 平年。
實現代碼
#include <stdio.h>
int is_leap_year(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int main(void) {
int year;
printf("請輸入年份: ");
scanf("%d", &year);
if (is_leap_year(year))
printf("%d 年是閏年\n", year);
else
printf("%d 年是平年\n", year);
return 0;
}
測試用例
| 年份 | 結果 | 說明 |
| 2000 | 閏年 | 400 整除 |
| 1900 | 平年 | 100 整除但非 400 |
| 2024 | 閏年 | 4 整除非 100 |
| 2023 | 平年 | 不可整除 |
| 1600 | 閏年 | 400 整除 |
| 1700 | 平年 | 100 整除非 400 |
擴展:某年某月天數
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];
}