## 選擇結構 ---- <style> .reveal .slides { text-align: left; } </style> 如果...,則...。 ---- ### if結構 ---- ```cpp= if(特定條件1) { 程式區塊... } else if(特定條件2) { 程式區塊... } else { 程式區塊... } ``` 白話一點,也就是**滿足特定條件1才會執行if大括號內的程式區塊,若沒有滿足特定條件1而有滿足特定條件2的話則執行else if大括號內的程式區塊,兩個特定條件都不滿足則執行else的。** ---- Example ```cpp= #include<iostream> using namespace std; int main() { int a = 2, b = 3; if(a > b) { printf("a>b"); //cout << "a>b"; } else if(a < b) { printf("a<b"); //cout << "a<b"; } else { printf("a=b"); } } ``` ---- ### 關係運算子 ---- 當我們在做**選擇判斷**時,會需要關係運算子來幫忙。 那其實關係運算子就跟我們數學的關係運算子只有一點點差別 : ---- * 大於(>) * 小於(<) * 大於等於(>=) * 小於等於(<=) * 等於(==) * 不等於(!=)。 ---- 沒錯,就是**等於跟不等於**最特別,不過在C++裡面,就是如此。 ---- Example ```cpp= #include<iostream> using namespace std; int main() { char grade; scanf("%c", &grade); //cin >> grade; if(grade == 'A') { printf("A"); } else if(grade == 'B') { printf("B"); } else { printf("C"); } } ``` ---- ### 邏輯運算子 ---- 有**且(AND / &)、或(OR / |)、非(NOT / !)**。 ---- 如果你想要a條件和b條件同時滿足再執行程式區塊的話,可以寫成這樣 : ```cpp= if(a && b){ 程式區塊... } ``` ---- 如果你想要a條件和b條件只要有一個滿足就執行程式區塊的話,可以寫成這樣 : ```cpp= if(a || b){ 程式區塊... } ``` ---- Example ```cpp= #include<iostream> using namespace std; int main() { int a; scanf("%d", &a); //cin >> a; if(a > 10 || a % 2 == 0) { printf("A condition"); } else { printf("None"); } } ``` ---- ```cpp= #include<iostream> using namespace std; int main() { int a; scanf("%d", &a); //cin >> a if(a > 10 && a % 2 == 0) { printf("B condition"); } else { printf("None"); } } ``` ---- ### 巢狀if ---- 白話來說,就是**if裡面再包if**。 ```c= if(特定條件1){ if(特定條件2){ 程式區塊1... } else{ 程式區塊2... } } ``` * 滿足特定條件1也**滿足**特定條件2,會執行程式區塊1。 * 滿足特定條件1但**不滿足**特定條件2,執行程式區塊2。 ---- Example ```cpp= #include<iostream> using namespace std; int main() { int a; scanf("%d", &a); //cin >> a; if(a > 0) { if(a % 2 == 0) { printf("A condition"); } else { printf("B condition"); } } else { printf("C condition"); } } ``` ---- ### switch ---- switch的架構: ```c= switch(變數名稱或運算式) { case 符合數字或字元: 程式區塊1; break; case 符合數字或字元: 程式區塊2; break; default: 程式區塊3; break; } ``` ---- 直接以例子來看,架設今天有一個整數型態的變數叫**grade**,如果**grade**等於1就輸出A,等於2就輸出B,其他數字就輸出C。 ```c= #include<stdio.h> int main() { int grade; scanf("%d", &grade); switch(grade) { case 1: printf("A"); break; case 2: printf("B"); break; default: printf("C"); break; } return 0; } ``` ---- 作業 (會寫的可以先寫) : * 10016 - 賣油翁 * 10017 - 公鹿二連霸 * 10018 - 身分證驗證 * 10019 - 閏年問題 ----
{"metaMigratedAt":"2023-06-17T04:21:52.121Z","metaMigratedFrom":"YAML","title":"程式設計培訓 - (3)","breaks":true,"slideOptions":"{\"theme\":\"solarized\",\"transition\":\"fade\"}","contributors":"[{\"id\":\"1dfd0d36-665c-414c-a3ba-995f194a8cb9\",\"add\":3307,\"del\":20}]"}
    139 views
   Owned this note