原問題「判斷一年有幾個月」顯為筆誤,實為「輸入年份、月份,輸出該月天數」。
int is_leap(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
switch-case 直觀版
int days_in_month(int year, int month) {
switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12: return 31;
case 4: case 6: case 9: case 11: return 30;
case 2: return is_leap(year) ? 29 : 28;
default: return -1; // 非法月份
}
}
int days_in_month(int year, int month) {
static const int days_common[12] = {31,28,31,30,31,30,31,31,30,31,30,31};
static const int days_leap[12] = {31,29,31,30,31,30,31,31,30,31,30,31};
if (month < 1 || month > 12) return -1;
return is_leap(year) ? days_leap[month-1] : days_common[month-1];
}
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 < 1 || month > 12) return -1;
int d = days[month-1];
if (month == 2 && is_leap(year)) d++;
return d;
}
#include
int is_leap(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 < 1 || month > 12) return -1;
int d = days[month-1];
if (month == 2 && is_leap(year)) d++;
return d;
}
int main(void) {
int year, month;
printf("請輸入年份: ");
if (scanf("%d", &year) != 1) return 1;
printf("請輸入月份 (1-12): ");
if (scanf("%d", &month) != 1) return 1;
int days = days_in_month(year, month);
if (days > 0)
printf("%d 年 %d 月 有 %d 天\n", year, month, days);
else
printf("月份錯誤 (1-12)\n");
return 0;
}
| 年份 | 月份 | 預期天數 | 說明 |
|---|---|---|---|
| 2024 | 2 | 29 | 閏年 |
| 1900 | 2 | 28 | 能被100整除但非400 → 平年 |
| 2000 | 2 | 29 | 能被400整除 → 閏年 |
| 2023 | 4 | 30 | 小月 |
| 2023 | 1 | 31 | 大月 |
| 2023 | 13 | -1 | 非法月份 |
int day_of_week(int y, int m, int d) {
if (m < 3) { m += 12; y--; }
int c = y / 100, k = y % 100;
int w = (k + k/4 + c/4 - 2*c + 26*(m+1)/10 + d - 1) % 7;
return (w + 7) % 7; // 0=Sun ... 6=Sat
}