模块 2 · 第 2 课(共 3)课程中的5/18~12 min
模块课程(2/3)
循环
只要条件保持为真,循环就允许重复执行代码块。
在 C++ 中,标准循环为:for、while 和 do-while。
for 循环
当您提前知道迭代次数时,将使用 for 循环:
C++
// Prints numbers from 0 to 4
for (int i = 0; i < 5; ++i) {
std::cout << i << " ";
}for 循环的结构分为三个部分,并用分号 ; 分隔:
- 初始化:在开始时仅运行一次(例如
int i = 0)。 - 条件:每次迭代前评估;如果为 false,则循环结束(例如
i < 5)。 - 更新:在每次迭代结束时运行(例如
++i)。
while 循环
只要条件为真,while 循环就会重复该代码。它通常在事先未知迭代次数时使用:
C++
int energy = 3;
while (energy > 0) {
std::cout << "Energy: " << energy << std::endl;
energy--; // Decrement to prevent an infinite loop
}do-while 循环
与 while 循环不同,do-while 循环保证循环体至少执行一次,因为条件是在最后评估的:
C++
int x = 10;
do {
std::cout << "Executed!" << std::endl;
} while (x < 5); // Condition is false, loop terminates after the first iteration自己尝试一下
锻炼#cpp.m2.l2.e1
尝试:0加载中...
使用 for 循环一次打印 1 到 5 之间的数字。
正在加载编辑器...
显示提示
使用语法“for (int i = 1; i <= 5; ++i) { ... }”。
3 次尝试后可用的解决方案
锻炼#cpp.m2.l2.e2
尝试:0加载中...
给定 count = 5,使用 while 循环打印 count 并在其大于 0 时将其递减。
正在加载编辑器...
显示提示
使用`while (count > 0) { ... }`并且不要忘记在循环内递减`count--`。
3 次尝试后可用的解决方案