
- C++ 基礎
- C++ 首頁
- C++ 概述
- C++ 環境設定
- C++ 基本語法
- C++ 註釋
- C++ Hello World
- C++ 省略名稱空間
- C++ 常量/字面量
- C++ 關鍵字
- C++ 識別符號
- C++ 資料型別
- C++ 數值資料型別
- C++ 字元資料型別
- C++ 布林資料型別
- C++ 變數型別
- C++ 變數作用域
- C++ 多個變數
- C++ 基本輸入/輸出
- C++ 修飾符型別
- C++ 儲存類
- C++ 運算子
- C++ 數字
- C++ 列舉
- C++ 引用
- C++ 日期和時間
- C++ 控制語句
- C++ 決策
- C++ if 語句
- C++ if else 語句
- C++ 巢狀 if 語句
- C++ switch 語句
- C++ 巢狀 switch 語句
- C++ 迴圈型別
- C++ while 迴圈
- C++ for 迴圈
- C++ do while 迴圈
- C++ foreach 迴圈
- C++ 巢狀迴圈
- C++ break 語句
- C++ continue 語句
- C++ goto 語句
- C++ 建構函式
- C++ 建構函式和解構函式
- C++ 複製建構函式
C++ if...else 語句
一個if語句可以後跟一個可選的else語句,當布林表示式為假時執行。
語法
C++ 中 if...else 語句的語法為:
if(boolean_expression) { // statement(s) will execute if the boolean expression is true } else { // statement(s) will execute if the boolean expression is false }
如果布林表示式計算結果為true,則將執行if 塊程式碼,否則將執行else 塊程式碼。
流程圖

示例
#include <iostream> using namespace std; int main () { // local variable declaration: int a = 100; // check the boolean condition if( a < 20 ) { // if condition is true then print the following cout << "a is less than 20;" << endl; } else { // if condition is false then print the following cout << "a is not less than 20;" << endl; } cout << "value of a is : " << a << endl; return 0; }
編譯並執行上述程式碼後,將產生以下結果:
a is not less than 20; value of a is : 100
if...else if...else 語句
一個if語句可以後跟一個可選的else if...else語句,這對於使用單個 if...else if 語句測試各種條件非常有用。
使用 if、else if、else 語句時,需要注意幾點。
一個 if 語句可以有零個或一個 else,並且它必須位於任何 else if 之後。
一個 if 語句可以有零個到多個 else if,並且它們必須位於 else 之前。
一旦 else if 成功,就不會測試任何剩餘的 else if 或 else。
語法
C++ 中 if...else if...else 語句的語法為:
if(boolean_expression 1) { // Executes when the boolean expression 1 is true } else if( boolean_expression 2) { // Executes when the boolean expression 2 is true } else if( boolean_expression 3) { // Executes when the boolean expression 3 is true } else { // executes when the none of the above condition is true. }
示例
#include <iostream> using namespace std; int main () { // local variable declaration: int a = 100; // check the boolean condition if( a == 10 ) { // if condition is true then print the following cout << "Value of a is 10" << endl; } else if( a == 20 ) { // if else if condition is true cout << "Value of a is 20" << endl; } else if( a == 30 ) { // if else if condition is true cout << "Value of a is 30" << endl; } else { // if none of the conditions is true cout << "Value of a is not matching" << endl; } cout << "Exact value of a is : " << a << endl; return 0; }
編譯並執行上述程式碼後,將產生以下結果:
Value of a is not matching Exact value of a is : 100
廣告