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

C 語言分支結構練習:switch-case 實現月份判斷季節

     編輯:關於C語言

問題描述

根據氣象劃分法:3-5 月春季,6-8 月夏季,9-11 月秋季,12-2 月冬季。輸入月份 (1-12),輸出對應季節。核心考點:switch-case 穿透特性、多標籤共用代碼塊、邊界輸入驗證。

標準實現

#include <stdio.h>

void season(int m);

int main() {
    int month;
    printf("請輸入月份: ");
    scanf("%d", &month);
    season(month);
    return 0;
}

void season(int m) {
    switch (m) {
        case 3: case 4: case 5:
            printf("您輸入的月份 %d 在春季\n", m);
            break;
        case 6: case 7: case 8:
            printf("您輸入的月份 %d 在夏季\n", m);
            break;
        case 9: case 10: case 11:
            printf("您輸入的月份 %d 在秋季\n", m);
            break;
        case 12: case 1: case 2:
            printf("您輸入的月份 %d 在冬季\n", m);
            break;
        default:
            printf("您輸入的數字不在 1-12 月份內!\n");
    }
}

switch-case 核心機制深度解析

1. 穿透與 break 的關鍵作用


// 無 break 的穿透行為(有時有用,多數是 Bug)
switch (m) {
    case 1: printf("一月");
    case 2: printf("二月");  // m=1 時也會執行!
    case 3: printf("三月");
    default: printf("其他");
}
// m=1 輸出: 一月二月三月其他

本題利用無 break 穿透實現「多月份共用一個輸出邏輯」,是 switch 的經典合法用法。

2. case 標籤要求:整型常量表達式

  • 合法:case 3:, case 'a':, case 1+2:
  • 非法:case x: (變量), case 1.5: (浮點), case "str": (字符串)

3. 實現原理:跳轉表 vs 比較鏈

  • 跳轉表:case 值連續密集時,編譯器生成數組索引跳轉,O(1)。
  • 二分查找/比較鏈:case 值稀疏時,退化為 if-else 鏈。
  • 本題 case 1-12 連續,極大概率生成跳轉表,效率極高。

替代方案對比

查表法實現(工程首選)


void season_lut(int m) {
    static const char *seasons[] = {
        "無效", "冬季", "冬季", "春季", "春季", "春季",
        "夏季", "夏季", "夏季", "秋季", "秋季", "秋季", "冬季"
    };
    if (m >= 1 && m <= 12)
        printf("月份 %d 在 %s\n", m, seasons[m]);
    else
        printf("無效月份 %d\n", m);
}

邊界測試用例

方案代碼優點缺點
switch (推薦)多 case 穿透跳轉表 O(1)、語義清晰、易維護僅支持整型常量
if-else 鏈if(m>=3&&m<=5)...支持任意條件表達式O(n) 比較、代碼冗長
查表法char* s[]={"冬","春","春"...}; puts(s[m]);極簡、O(1)、數據驅動需處理 m=0/>12 越界
數學公式(m%12+2)/3 映射 0-3無分支、極快可讀性差、邊界易錯
輸入預期輸出測試目的
3春季邊界起始
5春季邊界結束
12冬季跨年邊界
1冬季跨年邊界
0錯誤下界外
13錯誤上界外
-5錯誤負數

總結

switch-case 判斷季節是「多分支、整型常量、穿透特性」的教科書級案例。關鍵收穫:

  • 善用 case A: case B: case C: 穿透合並邏輯;
  • 理解跳轉表優化,case 值應盡量連續密集;
  • 工程中查表法 (LUT) 往往優於 switch/if:數據與邏輯分離、極簡、易擴展(如支持多語言季節名);
  • 永遠處理 default 情況,防禦性編程。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved