首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> C 語言問答

C 語言判斷某年某月天數:閏年規則、switch-case 實作與陣列查表優化

     編輯:C 語言問答

題目釐清

原問題「判斷一年有幾個月」顯為筆誤,實為「輸入年份、月份,輸出該月天數」。

閏年規則 (格里曆)

  • 能被 4 整除 **且** 不能被 100 整除 → 閏年。
  • 能被 400 整除 → 閏年。
  • 其餘 → 平年。

int is_leap(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

實作版本演進

版本 1: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; // 非法月份
    }
}

版本 2:陣列查表 (無分支、極快、易維護)


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];
}

版本 3:單一陣列 + 閏年修正 (最精簡)


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;
}

測試用例

年份月份預期天數說明
2024229閏年
1900228能被100整除但非400 → 平年
2000229能被400整除 → 閏年
2023430小月
2023131大月
202313-1非法月份

延伸:Zeller 同餘法算星期幾 (同樣需閏年判斷)


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
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved