首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> VC 教學

C++ 語言基礎:if 陳述句與迴圈(for/while/do-while)完整教學

     編輯:VC 教學

if 陳述句

測試條件,條件為真時執行一或多陳述句。

⚠ 陷阱:if 後不可加分號


if (x == 10); // 警告!多餘分號!
DoSomething(x); // 永遠執行,編譯器視為空陳述句

程式碼合法但無用,編譯器無法警告。

多行陳述句用大括號


if (x > 10) {
    cout << "The number is greater than 10" << endl;
    DoSomethingWithNumber(x);
}

C++ 速寫:直接用變數測試 true


if (fileGood) ReadData(); // 等同 if (fileGood == true)
bool fileGood = OpenSomeFile();
if (!fileGood) ReportError(); // 邏輯非測試 false

非零值即為 true,bool 或其他型別皆適用。

if-else 結構


if (x == 20) { DoSomething(x); }
else { DoADifferentThing(x); }

if-else if-else 鏈


if (cond_expr_1) { true_statements_1; }
else if (cond_expr_2) { true_statements_2; }
else { false_statements; }

迴圈

所有程式語言共同要素。用於陣列遍歷、重複動作、讀取檔案等。

三種迴圈:for、while、do-while。共同要素:起點、迴圈本體(通常在大括號)、終點、終止測試條件、可選 break/continue。

for 迴圈(最常用)

三參數:初始值、測試條件、遞增運算式。


for (initial; cond_expr; adjust) { statements; }
```
範例:
for (int i = 0; i < 10; i++) {
    cout << "This is iteration " << i << endl;
}

while 迴圈

僅有測試條件,每次迴圈開始檢查。條件為 true 持續執行。


int x;
while (x < 1000) {
    x = DoSomeCalculation(); // 假設最終回傳 >= 1000
}

常用 bool 變數控制:


bool done = false;
while (!done) {
    // some code
    done = SomeFunctionReturningBool();
    // more code
}

do-while 迴圈

與 while 類似,兩點不同:

  1. while 測試在迴圈開頭,do-while 測試在迴圈結尾。
  2. do-while 至少執行一次迴圈本體。

bool done = false;
do {
    // some code
    done = SomeFunctionReturningBool();
    // more code
} while (!done);

語法:


do { statements; } while (cond_expr);

選擇 while 還是 do-while 取決於迴圈本身邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved