C++ 循环
外观
C++循环[编辑 | 编辑源代码]
循环是C++控制流的核心结构之一,允许程序重复执行一段代码,直到满足特定条件。循环在自动化重复任务、遍历数据结构和实现算法时至关重要。C++提供了三种主要循环结构:for循环、while循环和do-while循环。
循环类型[编辑 | 编辑源代码]
for循环[编辑 | 编辑源代码]
for循环通常用于已知迭代次数的场景,语法结构如下:
for (初始化; 条件; 更新) {
// 循环体
}
示例:打印1到5的数字
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
return 0;
}
输出:
1 2 3 4 5
执行流程:
while循环[编辑 | 编辑源代码]
while循环在条件为真时持续执行,适合不确定迭代次数的场景:
while (条件) {
// 循环体
}
示例:用户输入验证
#include <iostream>
using namespace std;
int main() {
int password;
cout << "Enter password (1234): ";
cin >> password;
while (password != 1234) {
cout << "Wrong! Try again: ";
cin >> password;
}
cout << "Access granted!";
return 0;
}
输出(示例交互):
Enter password (1234): 1111 Wrong! Try again: 1234 Access granted!
do-while循环[编辑 | 编辑源代码]
与while类似,但保证至少执行一次循环体:
do {
// 循环体
} while (条件);
示例:菜单系统
#include <iostream>
using namespace std;
int main() {
char choice;
do {
cout << "\nMenu:\n1. Start\n2. Options\n3. Exit\nChoice: ";
cin >> choice;
// 处理选择...
} while (choice != '3');
return 0;
}
循环控制语句[编辑 | 编辑源代码]
语句 | 作用 | 示例 |
---|---|---|
break |
立即退出当前循环 | if (i == 3) break;
|
continue |
跳过当前迭代 | if (i%2 == 0) continue;
|
goto |
跳转到标签位置(慎用) | goto label;
|
嵌套循环[编辑 | 编辑源代码]
循环可以多层嵌套,常用于处理多维数据结构:
示例:乘法表
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= 9; j++) {
cout << i*j << "\t";
}
cout << endl;
}
return 0;
}
性能考量[编辑 | 编辑源代码]
循环效率直接影响程序性能,需注意:
- 减少循环内部的计算量
- 避免在循环条件中进行复杂运算
- 考虑循环展开(Loop Unrolling)优化
时间复杂度分析示例:
实际应用案例[编辑 | 编辑源代码]
案例:数据分析中的移动平均计算
#include <iostream>
#include <vector>
using namespace std;
vector<double> movingAverage(const vector<double>& data, int window) {
vector<double> result;
for (size_t i = 0; i <= data.size() - window; i++) {
double sum = 0;
for (int j = 0; j < window; j++) {
sum += data[i + j];
}
result.push_back(sum / window);
}
return result;
}
int main() {
vector<double> stockPrices = {45.3, 46.2, 47.8, 48.1, 47.5, 46.9};
auto averages = movingAverage(stockPrices, 3);
for (double avg : averages) {
cout << avg << " ";
}
return 0;
}
输出:
46.4333 47.3667 47.8 47.5
常见错误与调试[编辑 | 编辑源代码]
- 无限循环:忘记更新循环变量
- 差一错误:错误的条件边界
- 类型不匹配:循环变量与条件类型不一致
使用调试器逐步执行循环是排查问题的有效方法。
最佳实践[编辑 | 编辑源代码]
- 使用有意义的循环变量名(如
row
,col
而非i
,j
) - 保持循环体简洁(必要时提取为函数)
- 添加循环不变量的断言检查
- 考虑使用范围for循环(C++11起)简化集合遍历