while
?是 C 語言中的一種循環控制結構,用于在特定條件為真時重復執行一段代碼。
while 循環的語法如下:
while (條件表達式) {
? ? // 循環體:條件為真時執行的代碼
}
條件表達式
:返回真(非 0)或假(0)的表達式,決定是否繼續循環。- 大括號?
{}
:定義循環體,若只有一行語句,可省略,但建議保留以提高可讀性。
while 循環的核心是一個條件表達式,當條件為真(非 0)時,循環體內的代碼會反復執行,直到條件變為假(0)。while 循環的運行流程是:
- 檢查?
條件表達式
。 - 若為真,執行循環體,然后返回步驟 1。
- 若為假,退出循環,繼續執行后續代碼。
也就是說,while 循環的邏輯是:“只要條件成立,就繼續執行。”?
在 C語言中,while?循環特別適合那些循環次數不固定、依賴條件判斷的場景。接下來,我們將深入探討 while 循環的用法、使用場景以及注意事項。
【實例】簡單計數。
/**
* 系統學習C語言 https://xiecoding.cn/c/
**/
#include <stdio.h>int main(void) {int count = 0;while (count < 5) {printf("計數:%d\n", count);count++;}return 0;
}
輸出結果:
計數:0
計數:1
計數:2
計數:3
計數:4
count < 5
?初始為真,循環體執行 5 次,每次?count
?自增,直到?count = 5
,條件為假,循環結束。
while常見使用場景
1) 已知次數的循環
雖然?while
?更適合動態條件,但也可以用于固定次數的循環。
/**
* 系統學習C語言 https://xiecoding.cn/c/
**/
#include <stdio.h>int main(void) {int i = 1;while (i <= 10) {printf("%d ", i);i++;}printf("\n");return 0;
}
輸出結果:
1 2 3 4 5 6 7 8 9 10
2) 累加計算
用?while
?實現累加或求和。
/**
* 系統學習C語言 https://xiecoding.cn/c/
**/
#include <stdio.h>int main(void) {int sum = 0, num = 1;while (num <= 100) {sum += num;num++;}printf("1 到 100 的和是:%d\n", sum);return 0;
}
輸出結果:
1 到 100 的和是:5050
sum
?累加每次的?num
,直到?num > 100
。
3) 輸入驗證
while
?常用于等待用戶輸入符合條件。
/**
* 系統學習C語言 https://xiecoding.cn/c/
**/
#include <stdio.h>int main(void) {int num;printf("請輸入一個正數:");scanf("%d", &num);while (num <= 0) {printf("輸入錯誤,請輸入一個正數:");scanf("%d", &num);}printf("你輸入的正數是:%d\n", num);return 0;
}
輸出結果(示例輸入):
請輸入一個正數:-5
輸入錯誤,請輸入一個正數:0
輸入錯誤,請輸入一個正數:3
你輸入的正數是:3
C語言do-while循環
C語言還提供?do-while
?循環,與?while
?的區別是條件后置,至少執行一次循環體:
do {
? ? // 循環體:先執行一次
} while (條件表達式);
【實例】do-while 用法
/**
* 系統學習C語言 https://xiecoding.cn/c/
**/
#include <stdio.h>int main(void) {int num = 0;do {printf("num = %d\n", num);num++;} while (num < 3);return 0;
}
輸出結果:
num = 0
num = 1
num = 2
即使初始?num = 0
,循環體先執行一次,然后檢查條件。
while注意事項
1) 避免死循環
若條件永遠為真,會導致死循環。
// 錯誤示例
while (1) { printf("無限循環\n"); } // 死循環
解決方法:確保條件最終會變為假,或使用?break
?跳出。
2) break和continue
break
?立即退出循環,continue
?跳過本次循環剩余部分。
/**
* 系統學習C語言 https://xiecoding.cn/c/
**/
#include <stdio.h>int main(void) {int i = 0;while (i < 10) {i++;if (i == 3) continue; // 跳過 3if (i == 7) break; // 在 7 退出printf("%d ", i);}printf("\n");return 0;
}
輸出結果:
1 2 4 5 6
3) 條件表達式類型
條件必須返回整數值(非 0 為真,0 為假),避免使用浮點數直接比較。
// 不推薦
float f = 0.1;
while (f < 1.0) { ... } // 浮點誤差可能導致問題
總結
while 是 C 語言程序常用的一種循環結構,適合處理條件動態變化的重復任務。
學習 while 循環語句,除了它本身的語法外,你還需要掌握?do-while
?變體以及?break
、continue
?的用法,才能靈活控制程序的執行流程。
在 C 語言程序中使用 while 循環語句時,要避免出現死循環的情況。讀完本文,恭喜你已經徹底掌握 while 循環語句的用法。