Try  HackMD Logo HackMD

判斷式(If)

C++中的 if 語句是一種控制結構,用於根據條件執行特定的代碼區塊。if 語句允許程序根據不同的條件來選擇性地執行代碼,這是實現條件邏輯和決策的重要工具。

零、方塊

  • 方塊位置:條件與迴圈
  • 方塊圖片
    Image Not Showing Possible Reasons
    • The image was uploaded to a note which you don't have access to
    • The note which the image was originally uploaded to has been deleted
    Learn More →

一、if 語句的基本結構

if 語句的基本語法如下:

if (條件) { // 當條件為真(true)時執行的代碼 }
  • 條件:一個返回布爾值的表達式(即 truefalse)。
  • 代碼區塊:當條件為真時要執行的代碼,位於大括號 {} 中。如果只有一條語句,則可以省略大括號。

二、if 語句的用法

1. 單一 if 語句

這是最基本的形式,當條件為真時執行特定代碼。

#include <bits/stdc++.h> using namespace std; int main() { int number; cout << "請輸入一個整數:"; cin >> number; if (number > 0) { cout << "輸入的數字是正數。" << endl; } return 0; }
  • 方塊
    Image Not Showing Possible Reasons
    • The image was uploaded to a note which you don't have access to
    • The note which the image was originally uploaded to has been deleted
    Learn More →

2. if-else 語句

使用 else 可以提供在條件為假時的替代行為。

#include <bits/stdc++.h> using namespace std; int main() { int number; cout << "請輸入一個整數:"; cin >> number; if (number > 0) { cout << "輸入的數字是正數。" << endl; } else { cout << "輸入的數字不是正數。" << endl; } return 0; }
  • 方塊
    Image Not Showing Possible Reasons
    • The image was uploaded to a note which you don't have access to
    • The note which the image was originally uploaded to has been deleted
    Learn More →

3. if-else if-else 結構

當需要檢查多個條件時,可以使用 else if 結構。

#include <bits/stdc++.h> using namespace std; int main() { int number; cout << "請輸入一個整數:"; cin >> number; if (number > 0) { cout << "輸入的數字是正數。" << endl; } else if (number < 0) { cout << "輸入的數字是負數。" << endl; } else { cout << "輸入的數字是零。" << endl; } return 0; }
  • 方塊
    Image Not Showing Possible Reasons
    • The image was uploaded to a note which you don't have access to
    • The note which the image was originally uploaded to has been deleted
    Learn More →

三、使用邏輯運算符的條件

可以使用邏輯運算符來組合多個條件,如 &&(AND)、||(OR)和 !(NOT)。

#include <bits/stdc++.h> using namespace std; int main() { int age; cout << "請輸入年齡:"; cin >> age; if (age < 0) { cout << "年齡不能為負數。" << endl; } else if (age < 18) { cout << "未成年人。" << endl; } else if (age < 65) { cout << "成年人。" << endl; } else { cout << "老年人。" << endl; } return 0; }
  • 方塊
    Image Not Showing Possible Reasons
    • The image was uploaded to a note which you don't have access to
    • The note which the image was originally uploaded to has been deleted
    Learn More →

四、巢狀 if 語句

if 語句可以嵌套在其他 if 語句中,這樣可以對更複雜的邏輯進行判斷。

#include <bits/stdc++.h> using namespace std; int main() { int number; cout << "請輸入一個整數:"; cin >> number; if (number != 0) { if (number > 0) { cout << "輸入的數字是正數。" << endl; } else { cout << "輸入的數字是負數。" << endl; } } else { cout << "輸入的數字是零。" << endl; } return 0; }
  • 方塊
    image

五、總結

  • if 語句用於條件判斷,根據條件的真假來執行相應的代碼。
  • 可以使用 elseelse if 擴展條件處理。
  • 邏輯運算符可以用於組合多個條件。
  • if 語句可以巢狀使用,以實現更複雜的邏輯判斷。

六、if 語句的注意事項

  • 確保條件表達式返回布爾值,避免不必要的錯誤。
  • 儘量避免過多的巢狀結構,以提高代碼的可讀性。
  • 使用適當的縮排和註釋來增加代碼的可維護性。

By Ericbob