while (condition) { body }:當條件為真持續執行本體。條件為布林運算式,本體可為單一陳述式或區塊 { ... }。屬於先測試後執行迴圈,可能零次執行。
┌─────────┐
│ condition │──False──→ 結束
└────┬────┘
│ True
▼
┌─────────┐
│ body │
└────┬────┘
│
└──────┘
// 1 到 10 累加
int sum = 0, i = 1;
while (i <= 10) {
sum += i;
i++;
}
Console.WriteLine(sum); // 55
// 讀取輸入直到 "exit"
string line;
while ((line = Console.ReadLine()) != "exit") {
Console.WriteLine($"Echo: {line}");
}
// 巢狀迴圈:九九乘法表
int row = 1;
while (row <= 9) {
int col = 1;
while (col <= row) {
Console.Write($"{col}x{row}={col*row}\t");
col++;
}
Console.WriteLine();
row++;
}
| 錯誤類型 | 原因 | 修正 |
|---|---|---|
| 無限迴圈 | 條件永遠為真、遞增邏輯錯誤 | 檢查條件變數更新、加入安全計數器 |
| 離一錯誤 | <= vs <、起始值偏移 | 邊界測試:0, 1, max, max+1 |
| 變數未初始化 | 條件使用未賦值變數 | 宣告時指派初值 |
// 模式 1:旗標控制
bool running = true;
while (running) {
// ...
if (shouldStop) running = false;
}
// 模式 2:TryParse 迴圈
int number;
while (!int.TryParse(Console.ReadLine(), out number)) {
Console.WriteLine("格式錯誤,請重新輸入整數:");
}
// 模式 3:資料流讀取
using (var reader = new StreamReader("data.txt")) {
string line;
while ((line = reader.ReadLine()) != null) {
ProcessLine(line);
}
}
// 模式 4:非同步輪詢 (配合 Task.Delay)
while (!cancellationToken.IsCancellationRequested) {
await DoWorkAsync();
await Task.Delay(1000, cancellationToken);
}




