# if-else 與多重 if-else ## **if-else**  - if-else 的使用方法 當條件成立時執行if{}內的,反之執行else{}內 ```c= if (條件) { 當條件成立時..... } else { 當條件未成立時.... } ``` - if-else 的示範 👉 ``` c= #include <stdio.h> int main() { int a = 9 , b = 0; if (a > b) { printf("Yes, a > b\n"); } else { printf("NO, a < b\n"); } } ``` ## **多重if-else** - if-else 的使用方法 ```c= if (條件一) { 當條件一成立時..... } else if (條件二) { 當條件二成立時..... } else { 當條件都未成立時..... } ``` - 多重 if-else 的示範 👉 ```c= #include <stdio.h> int main() { int Number = 0; scanf("%d",&Number); if (Number == 1) { printf("Number is 1.\n"); } else if (Number == 2) { printf("Number is 2.\n"); } else { printf("Number just have 1 or 2.\n"); } } ``` <div style=" border:2px padding : 10px; background-color:#BBFFFF; color:#003060;width: 50%;"> 特別的示範 :exclamation: 如果if跟else if的判斷式相同會發生甚麼?? </div> ```c= #include <stdio.h> int main() { int Number = 1; if (Number == 1) { printf("Number is 1.\n"); } else if (Number == 1) { printf("Number is 2.\n"); } else { printf("Number just have 1 or 2.\n"); } return 0; } ``` 會發現到輸出的是 `Number is 1.` <font color = apple> 原因是因為當我們判斷if成功的時候,就會直接出這個判斷式,所以接下來的`else if`就不會去判斷到 </font><br> ---- # 布林值 - bool 的使用方法 要 `#include <stdbool.h>` 所謂的布林函數 (Boolean function) 是指傳回真假值的函數 (function) ,由於 C 語言中運算式 (expression) 結果為 0 就表示假 (false) ,非 0 值就表示真 (true) ,所以當函數傳回 0 或非 0 值時,就可以當作布林函數來使用。 - bool 的示範 👉 ```c= #include <stdio.h> #include <stdbool.h> int main() { bool judge = true; if (judge) { printf("這是正確的\n"); } else { printf("這是錯誤的\n"); } return 0; } ``` ---- 課堂練習: [W3school](https://www.w3schools.com/c/exercise.php?filename=exercise_conditions4) [UVa](https://oj.fcu.edu.tw/problem/Uva10035) [UVa的答案](https://youtu.be/TObf0FOqaTg?si=3swXPQvYtp0XgjXC) ---- 參考 : [if-else](https://www.runoob.com/cprogramming/c-if-else.html) [bool](http://kaiching.org/pydoing/c/c-boolean.html)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up