![]() |
C 教材:層層相套的 if-else |
在前面,我們看到 if-else 結構的 STATEMENTS_0 裡面, 可以有另一個 if 結構。 事實上,STATEMENTS_0 裡面可以有另一個 if-else 結構, 而第二個 else 的 STATEMENTS_0 部份又可以有一個 if-else 結構。 這樣下去,沒有理論上的上限。 這樣的結構,稱為層層相套的 if (nested if)。 例如以下的程式片段 (需要在其前後補上適當的宣告和指令,才能執行), 就一共套了四層的 if-else 結構。
if (c >= '0' && c <= '9') ++ndigit; else if (c == ' ' || c == '\t') ++nwhite; else if (c >= 'a' && c <= 'z') ++nsmall; else if (c >= 'A' && c <= 'Z') ++ncapital; else ++nother;這個程式片段,企圖將輸入的字元分成五類,分別記錄它們出現的次數。 檢查的項目依序是:數字、空白、小寫字母、大寫字母、其他。
else 語句必定是跟隨最靠近的一個 if 語句。 以下是個常犯的錯誤,我們的眼睛常會被排版格式給欺騙了。 要知道,C 是看不到排版格式的,對它來說,指令與指令之間的空白,是不存在的。 以下的變數都假設是 int 型態。
if (n >= 0) for (i=0; i < n; ++i) if (i*n >= 100) printf("%d\n", i); else printf("%d is negative.\n", n);前面的 else 其實是在
if (n >= 0) { for (i=0; i < n; ++i) if (i*n >= 100) printf("%d\n", i); } else printf("%d is negative.\n", n);或者
if (n >= 0) for (i=0; i < n; ++i) { if (i*n >= 100) printf("%d\n", i); } else printf("%d is negative.\n", n);都可以。
習題
if (c >= '0' && c <= '9') ++ndigit; else if (c == ' ' || c == '\t') ++nwhite; else if (c >= 'a' && c <= 'z') ++nsmall; else if (c >= 'A' && c <= 'Z') ++ncapital; else ++nother;中的倒數兩個 if,若改寫成
if (c >= 'A' && c <= 'z') ++nalphabet;則 nalphabet 是否恰好記錄了所有英文字母的出現次數? 也就是說,nalphabet 是否等於 nsmall + ncapital? 解釋您的答案。
if (c >= '0' && c <= '9') ++ndigit; else if (c == ' ' || c == '\t') ++nwhite; else if (c >= 'a' && c <= 'z') ++nsmall; else if (c >= 'A' && c <= 'Z') ++ncapital; else ++nother;
![]() |
![]() |
單維彰 (2000/03/31) --- |