C++ continue 语句用法及实例
本文中我们学习如何在循环中使用 continue
语句跳过循环中的当前迭代。
在 C++ 编程中,continue
语句用于跳过循环的当前迭代并且程序的控制进入下一次迭代。
在您了解 continue
语句之前,请确保您了解,
C++ continue 语句工作原理
下图展示了 continue
的工作流程:
示例 1:在 for 循环中使用 continue
在 for
循环中, continue
跳过当前迭代并且控制流跳转到 update
表达式。
以下程序当 i == 3
时跳过当前跌倒。
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
// 满足条件时跳过当前迭代
if (i == 3) {
continue;
}
cout << i << endl;
}
return 0;
}
输出
1
2
4
5
在上面的程序中,我们使用了 for
循环在每次迭代中打印 i
变量。在这里,注意代码,
if (i == 3) {
continue;
}
这意味着
- 当
i
等于3
时,continue
语句跳过当前迭代并开始下一次迭代 - 然后,
i
变成4
,然后再次计算条件表达式。 - 因此, 在接下来的两次迭代中打印
4
和5
。
注意:continue
语句几乎总是与决策语句一起使用。
示例 2:在 while 循环中使用 continue
在 while
循环中, continue
跳过当前迭代,程序的控制流跳回到 while
循环的条件判断。
以下程序累加用户输入的不大于 50
的正数。当输入负数时,循环终止。当输入大于 50
的数时,跳过当前迭代。
#include <iostream>
using namespace std;
int main() {
int sum = 0;
int number = 0;
while (number >= 0) {
// 累加所有正数
sum += number;
// 获取用户输入的数字
cout << "Enter a number: ";
cin >> number;
// continue 条件
if (number > 50) {
cout << "The number is greater than 50 and won't be calculated." << endl;
number = 0; // the value of number is made 0 again
continue;
}
}
// display the sum
cout << "The sum is " << sum << endl;
return 0;
}
输出
Enter a number: 12
Enter a number: 0
Enter a number: 2
Enter a number: 30
Enter a number: 50
Enter a number: 56
The number is greater than 50 and won't be calculated.
Enter a number: 5
Enter a number: -3
The sum is 99
在上面的程序中,用户持续输入一个数字。while
循环用于打印由用户输入的正数的总和,只要输入的号码是不大于 50
。
注意 continue
语句的使用。
if (number > 50){
continue;
}
- 当用户输入大于
50
的数字时,continue
语句将跳过当前迭代。然后程序的控制流程进入while
循环。 - 当用户输入一个小于 的数字时
0
,循环终止。
注意:continue
语句对 do...while
循环的工作方式相同。
继续嵌套循环
当 continue
与嵌套循环一起使用时,它会跳过内部循环的当前迭代。例如,
#include <iostream>
using namespace std;
int main() {
int number;
int sum = 0;
// first loop
for (int i = 1; i <= 3; i++) {
// second loop
for (int j = 1; j <= 3; j++) {
if (j == 2) {
continue;
}
cout << "i = " << i << ", j = " << j << endl;
}
}
return 0;
}
输出
i = 1, j = 1
i = 1, j = 3
i = 2, j = 1
i = 2, j = 3
i = 3, j = 1
i = 3, j = 3
在上面的程序中,当 continue
语句执行时,它会跳过内循环中的当前迭代。并且程序的控制移到了内循环的更新表达式上。
因此, j = 2
永远不会显示在输出中。
注意:break 语句完全终止循环。但是,continue
语句仅跳过当前迭代。