使用 continue 语句跳过循环迭代
在这一步中,你将学习如何在 C++ 中使用 continue
语句跳过当前循环迭代并进入下一次迭代。continue
语句允许你根据特定条件选择性地跳过循环的某些部分。
首先,导航到项目目录并创建一个新的 C++ 文件:
cd ~/project
touch continue_statement.cpp
在 WebIDE 中打开 continue_statement.cpp
文件,并添加以下代码以探索使用 continue
语句的不同方式:
#include <iostream>
int main() {
// 在循环中跳过偶数
std::cout << "Printing odd numbers between 1 and 10:" << std::endl;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
continue; // 跳过偶数
}
std::cout << i << " ";
}
std::cout << std::endl;
// 在求和计算中过滤掉负数
int sum = 0;
int numbers[] = {5, -3, 10, -7, 8, -2, 15};
int arraySize = sizeof(numbers) / sizeof(numbers[0]);
std::cout << "\nCalculating sum of positive numbers:" << std::endl;
for (int j = 0; j < arraySize; j++) {
if (numbers[j] < 0) {
continue; // 跳过负数
}
sum += numbers[j];
std::cout << "Added: " << numbers[j] << ", Current Sum: " << sum << std::endl;
}
std::cout << "Final Sum of Positive Numbers: " << sum << std::endl;
return 0;
}
编译并运行程序:
g++ continue_statement.cpp -o continue_statement
./continue_statement
示例输出:
Printing odd numbers between 1 and 10:
1 3 5 7 9
Calculating sum of positive numbers:
Added: 5, Current Sum: 5
Added: 10, Current Sum: 15
Added: 8, Current Sum: 23
Added: 15, Current Sum: 38
Final Sum of Positive Numbers: 38
continue
语句的关键特性:
- 跳过当前循环迭代的剩余部分
- 将控制权转移到循环的下一次迭代
- 可以在
for
、while
和 do-while
循环中使用
- 适用于过滤或条件处理
continue
语句的重要用途:
- 根据条件跳过特定迭代
- 在循环中过滤数据
- 避免不必要的计算
- 简化循环逻辑