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

C語言條件控制語句(三):switch 多路分支與一元二次方程求解

     編輯:C 語言基礎

switch 多路分支語句

if 語句只能處理二選一的情況,當需要實現多種可能之一時,若使用多重 if...else if 或嵌套 if,程式碼會變得冗長且可讀性降低。C 語言提供了 switch 開關語句專門處理多路分支,使程式更簡潔。

switch 語法格式

switch (表達式) {
    case 常量表達式1: 語句序列1; break;
    case 常量表達式2: 語句序列2; break;
    ...
    case 常量表達式n: 語句n; break;
    default: 語句n+1;
}

其中常量表達式的值必須是整型、字符型或枚舉類型。各語句序列允許有多條語句,不需用大括號括起。若某 case 的語句序列為空,對應的 break 可省略。

多值共用同一處理邏輯

當多個 case 需執行相同語句時,可堆疊 case 標籤:

switch(i) {
    case 1:
    case 2:
    case 3: 語句1; break;
    case 4:
    case 5: 語句2; break;
    default: 語句3;
}

當 i 為 1、2 或 3 時執行語句1;為 4 或 5 時執行語句2;否則執行語句3。

範例 1:輸入月份印出 1999 年該月天數

#include <stdio.h>

int main() {
    int month, day;
    printf("please input the month number: ");
    scanf("%d", &month);
    
    switch(month) {
        case 1: case 3: case 5: case 7: case 8: case 10: case 12:
            day = 31; break;
        case 4: case 6: case 9: case 11:
            day = 30; break;
        case 2:
            day = 28; break;
        default:
            day = -1;
    }
    
    if (day == -1)
        printf("Invalid month input!\n");
    else
        printf("1999.%d has %d days\n", month, day);
    return 0;
}

範例 2:解一元二次方程 ax² + bx + c = 0

使用嵌套 if 處理各種係數情況:

  • a = 0:退化為一次方程或無解/不定根
  • a ≠ 0:判別式 Δ = b² - 4ac 決定根的類型(兩不等實根、兩相等實根、共軛複根)
#include <math.h>
#include <stdio.h>

int main() {
    float a, b, c, s, x1, x2;
    double t;
    printf("please input a,b,c: ");
    scanf("%f%f%f", &a, &b, &c);
    
    if (a == 0.0) {
        if (b != 0.0)
            printf("the root is: %f\n", -c/b);
        else if (c == 0.0)
            printf("x is inexactive\n");
        else
            printf("no root!\n");
    } else {
        s = b*b - 4*a*c;
        if (s >= 0.0) {
            if (s > 0.0) {
                t = sqrt(s);
                x1 = (-b + t) / (2*a);
                x2 = (-b - t) / (2*a);
                printf("There are two different roots: %f and %f\n", x1, x2);
            } else {
                printf("There are two equal roots: %f\n", -b/(2*a));
            }
        } else {
            t = sqrt(-s);
            x1 = -b / (2*a);        // 實部
            x2 = fabs(t / (2*a));   // 虛部絕對值
            printf("There are two virtual roots:\n");
            printf("%f + i%f\t%f - i%f\n", x1, x2, x1, x2);
        }
    }
    return 0;
}

執行結果範例

RUN
please input a,b,c: 1 2 3
There are two virtual roots:
-1.000000 + i1.000000    -1.000000 - i1.000000

RUN
please input a,b,c: 2 5 3
There are two different roots: -1.000000 and -1.500000

RUN
please input a,b,c: 0 0 3
No root!
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved