C/分支結構

維基教科書,自由的教學讀本
< C

導論[編輯]

在前面認識了基本的數據結構與輸入輸出後,你或許會想,「要是我想根據使用者的輸入值,輸出不同結果時該怎麼做?」

就像這樣:

如果 ( 輸入1 )
    做這些事
    ...
如果 ( 輸入2 )
    做這些事
    ...
如果 ( 輸入3 )
    做這些事
    ...
...

這時候就需要運用 if/else 與 switch 句型進行判斷了

判斷[編輯]

if/else 子句[編輯]

最基本的判斷子句,格式如下:

if ( 條件1 )
{
    // 條件1成立時執行
}

也可以加上 else,這樣當條件不成立時,else 內的敘述句就會執行

if ( 條件1 )
{
    // 條件1成立時執行
}
else
{
    // 條件1不成立時執行
}

例如判斷使用者輸入的整數是否為正數

#include<stdio.h>
int main ( int argc, int argv[] )
{
    int a;
    scanf("%d", &a);
    if ( a <= 0 )
    {
        // a 不為正數時執行此行
        printf("Wrong number!");
    }
    else
    {
        // a 為正數時執行此行
        printf("You entered %d.", a);
    }
    
    return 0;
}
// 使用者輸入:5     輸出:You entered 5.
// 使用者輸入:-2    輸出:Wrong number!

一般來說,若 if/else 子句後的敘述句只有一行時不須加上大括號{}

#include<stdio.h>
int main ( int argc, int argv[] )
{
    int a;
    scanf("%d", &a);
    if ( a <= 0 )
        printf("Wrong number!"); // a 不為正數時執行此行
    else
        printf("You entered %d.", a); // a 為正數時執行此行

    return 0;
}

但還是建議養成在每一個 if/else 子句後面加上大括號的習慣,這樣不僅可以增加程式的易讀性,也可以在建立大型專案時便於維護與修改

switch 子句[編輯]

//for Ex.
#include <stidio.h>
main()
{
    int score=3; /*以5分制成绩为例*/
    switch(c)    /*如果结果为3,则打印字符串*/
    {
        case 5 : printf("Great!");
        case 4 : 
        case 3 : printf("Your score is %d \n",c); break;
        default: printf("You may need to work harder");
    }

    return 0;
}

邏輯運算子[編輯]

結語[編輯]

在C語言可以運用 if/else 句型與 switch 句型進行條件判斷