if / else
if/else
允許比基本的 if
更精細地控制程式碼的運行,讓多個條件測試可以結合在一起運行;例如,測試一個類比輸入值,根據是否小於 500、等於 500 或大於 500,分別執行不同動作。下面是一個 if/else
程式碼範例:
if (pinFiveInput < 500) { // 動作 A } else { // 動作 B }
else
可以放在另一個 if
之前,以形成多個互斥且同時運行的條件測試。其中,每個條件測試會依序被執行,直到有一條件測試成立,然後執行關連此條件的程式碼區塊,略過後續的其它條件測試。如果整個過程沒有任何條件測試成立,則會執行最後面的 else
區塊(如果此區塊存在的話。)
注意一個 else if
區塊可以擁有一個終止的 else
區塊,但也可以沒有。且 else if
的分支數目可以任意多,沒有限制。
if (pinFiveInput < 500) { // 執行區塊 A } else if (pinFiveInput >= 1000) { // 執行區塊 B } else { // 執行區塊 C }
另一種表示分支且可同時做多個互斥的條件測試的方法是 switch case
敘述。
See also
本頁由熱血青年 LBU 譯自英文版。
The text of the 86Duino reference is a modification of the Arduino reference, and is licensed under a Creative Commons Attribution-ShareAlike 3.0 License. Code samples in the reference are released into the public domain.