跳轉到內容

程式設計基礎/巢狀 if then else

來自華夏公益教科書,開放的書籍,開放的世界

雙向選擇結構可以巢狀在其他雙向選擇結構中,從而形成多路選擇。

我們首先要介紹巢狀控制結構的概念。巢狀是指將一個專案放在另一個專案內部。例如

if expression
    true action
else 
    false action

這是 if then else 控制結構的基本形式。現在考慮

if age is less than 18
    you can't vote
    if age is less than 16
        you can't drive
    else
        you can drive
else 
    you can vote
    if age is less than 21
        you can't drink 
    else
        you can drink

如你所見,我們只是在“真操作”部分添加了一個語句和另一個 if then else 控制結構。我們對“假操作”也進行了相同的操作(嵌套了另一個 if then else)。在我們的例子中,我們嵌套了 if then else 控制結構。巢狀可以將 if then else 放在 while 迴圈中。因此,巢狀的概念允許混合使用不同型別的控制結構。

多路選擇

[編輯 | 編輯原始碼]

雙向選擇的一個缺點是我們只能考慮兩種選擇。但如果你有多於兩種選擇怎麼辦?考慮以下有四種選擇的情況

if age equal to 18
    you can now vote
else
    if age equal to 39
        you are middle-aged 
    else
        if age equal to 65
            you can consider retirement
        else
            your age is unimportant

根據 age 的值,你會得到相應的提示。最後一個專案被稱為預設值。如果 age 不等於 18、39 或 65,你就會收到預設提示。為了簡化程式碼結構,通常將其寫成

if age equal to 18
    you can now vote
else if age equal to 39
    you are middle-aged 
else if age equal to 65
    you can consider retirement
else
    your age is unimportant

關鍵詞

[編輯 | 編輯原始碼]
多路選擇
使用控制結構從多個選項中進行選擇。
巢狀控制結構
將一個控制結構放在另一個控制結構內部。

參考文獻

[編輯 | 編輯原始碼]
華夏公益教科書