# Review ## 運算子與選擇結構 :::warning * 你習慣撰寫什麼風格的程式碼呢? ::: ### 示例 > 輸入一個整數,若數字介於 $50$~$100$ 之間,則輸出`Yes`,否則輸出`No`。 ::: spoiler 法一:if-else if-else ```cpp= // 前略 int num; cin >> num; if(num < 50){ cout << "No" << endl; }else if(num <= 100){ cout << "Yes" << endl; }else { cout << "No" << endl; } ``` ::: ::: spoiler 法二:if-else ```cpp= // 前略 int num; cin >> num; if(num >= 50 && num <= 100){ cout << "Yes" << endl; } else { cout << "No" << endl; } ``` ::: ::: spoiler 法三:三元運算子 ```cpp= int num; cin >> num; cout << (num >= 50 && num <= 100?"Yes":"No") << endl; ``` ::: ## 運算子的優先順序  ### 偵錯練習 承上例,請舉出一個會出錯的輸入數字。 ::: danger Code 1: ```cpp= // 前略 int num; cin >> num; if(num >= 50){ cout << "No" << endl; }else if(num <= 100){ cout << "Yes" << endl; }else { cout << "No" << endl; } ``` Code 2: ```cpp= // 前略 int num; cin >> num; if(50 <= num <= 100){ cout << "Yes" << endl; }else { cout << "No" << endl; } ``` ::: ### 經典示例 :::warning - 根據運算子的優先順序,如何以中文解釋以下程式碼? - 為什麼某些地方要加/不用加大括弧/小括弧呢? ::: #### 1) [格瑞哥里的煩惱(閏年判斷)](https://zerojudge.tw/ShowProblem?problemid=d067) > 輸入只有一行,其中含有一個正整數 y,代表西元年份。若 y 是閏年,請輸出「a leap year」,否則請輸出「a normal year」。 ```cpp= #include <iostream> using namespace std; int main() { int y; cin >> y; if(y%400==0 || y%4==0 && y%100!=0) cout << "a leap year" << endl; else cout << "a normal year" << endl; } ``` #### 2) [我愛偶數](https://zerojudge.tw/ShowProblem?problemid=d485) > 輸入只有一行,其中含有兩個由空白隔開的整數 a, b (0 ≤ a ≤ b ≤ 2147483647)。輸出一個整數,代表 a 與 b 之間 (含 a 與 b) 一共有多少個偶數。 ```cpp= #include <iostream> using namespace std; int main() { long long n, m; cin >> n >> m; cout << ((m-n)+(n%2==0)+(m%2==0))/2 << endl; } ``` ## 計數變數的生命週期 ```cpp= for(int i = 0; i < 5; i++) cout << i << endl; cout << i << endl; ``` 以上這段程式碼,編譯時就會出現錯誤: :::danger ``` error: ‘i’ was not declared in this scope ``` ::: 這是因為變數`i`被宣告在`for`迴圈裡面。一但離開迴圈,`i`的生命就走到了盡頭。如果還想在迴圈外繼續存取這個變數,可以做這樣的修改: ```cpp= int i; for(i = 0; i < 5; i++) cout << i << endl; cout << i << endl; ``` 以上這段程式碼,將變數`i`宣告在`for`迴圈之外,因此在離開迴圈後,`i`仍繼續存在。程式可正常編譯,輸出結果為: ``` 0 1 2 3 4 5 ``` 其中數字`5`為離開迴圈後輸出的結果。
×
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