C++嵌套循环,外部有变量
C++ nested loops with variables outside
这绝对是一个愚蠢的问题,已经回答了多次,但我真的很困惑,找不到如何谷歌。
我有大约 4 年的软件开发经验,但这件事让我不知所措:
int x1 = 2, x2 = 5;
int y1 = 2, y2 = 5;
for (; x1 <= x2; x1++) {
for (; y1 <= y2; y1++) {
cout << x1 << " : " << y1 << endl;
}
}
结果是
2 : 2
2 : 3
2 : 4
2 : 5
但我期待看到:
2 : 2
2 : 3
2 : 4
2 : 5
3 : 2
3 : 3
3 : 4
...
5 : 4
5 : 5
我的意思是x1甚至没有更新一次。
我认为这与外部作用域和编译器优化有关。请澄清我。
您没有重置 y1。
int x1 = 2, x2 = 5;
int y2 = 5;
for (; x1 <= x2; x1++) {
for (y1 = 2; y1 <= y2; y1++) { // This resets y1 every time the loop starts
cout << x1 << " : " << y1 << endl;
}
}
或
int x1 = 2, x2 = 5;
int y1 = 2, y2 = 5;
for (; x1 <= x2; x1++) {
y1 = 2;
for (; y1 <= y2; y1++) {
cout << x1 << " : " << y1 << endl;
}
}
此行为是正确的。
在嵌套循环之后,您再也不会设置y1=2;
,因此cout << x1 << ":" << y1 endl
永远不会再次运行,因为当嵌套循环结束时 y1 为 6,因此不符合嵌套循环中给出的条件 (y1 <= y2
)。
编辑:有关工作代码,请参阅user9335240的评论
您应该重置y1的值,可以通过上述步骤完成,如发布或如下所示:
int x1 = 2, x2 = 5;
int y2 = 5;
for (; x1 <= x2; x1++) {
for (; y1 <= y2; y1++) { // This resets y1 every time the loop starts
cout << x1 << " : " << y1 << endl;
}
y1 = 2;
}
问题出在inner for-loop
上。 在第一次迭代中(当x1
2
时),你会得到打印的结果,即
2 : 2
2 : 3
2 : 4
2 : 5
由于您尚未重新初始化y2
变量,因此,在内部循环的所有后续迭代中,条件y1 <= y2
的计算结果为false
(此时在本例中y2
6
)。因此,您没有按预期获得输出。
您可以通过以下修改后的代码来确认这一点:
int x1 = 2, x2 = 5;
int y1 = 2, y2 = 5;
for (; x1 <= x2; x1++)
{
for (; y1 <= y2; y1++)
{
cout << x1 << " : " << y1 << endl;
}
cout<<"In outer loop with x1="<<x1<<" and y1="<<y1<<endl;
}
您将获得以下输出:
Point 1: In outer loop with x1=2 and y1=2
2 : 2
2 : 3
2 : 4
2 : 5
Point 2: In outer loop with x1=2 and y1=6
Point 1: In outer loop with x1=3 and y1=6
Point 2: In outer loop with x1=3 and y1=6
Point 1: In outer loop with x1=4 and y1=6
Point 2: In outer loop with x1=4 and y1=6
Point 1: In outer loop with x1=5 and y1=6
Point 2: In outer loop with x1=5 and y1=6
要按预期获得输出,请重新初始化y1
以在内部循环中2
,即将内部循环从for (; y1 <= y2; y1++)
更改为for (y1 = 2; y1 <= y2; y1++)
这就是为什么你应该像下面这样对for
循环进行编码以避免这种副作用,这样你就不会忘记在这种情况下重新初始化计数器变量y1
。此外,在循环for
声明和初始化计数器变量不会给您带来任何优势。因此,请始终尝试避免这种实现并遵循以下方法:
int x2 = 5;
int y2 = 5;
for (int x1 = 2; x1 <= x2; x1++) {
for (int y1 = 2; y1 <= y2; y1++) {
cout << x1 << " : " << y1 << endl;
}
}
相关文章:
- 在类函数中初始化外部作用域变量
- 如果全局变量默认是外部变量,为什么要添加"extern"关键字?
- 同时具有"外部"和"内联"说明符的变量
- 访问 PlatformIO 中的外部环境变量
- 如何在函数外部访问函数中局部变量的值?
- 堆栈/帧指针作为外部变量
- 使用外部文件中的变量进行视觉C++
- 内联函数/变量的外部链接
- 当使用lambda进行变量的复杂初始化时,如何处理从内部抛出的lambda外部异常
- const_cast const 方法中的"this"将"this"分配给外部变量?
- 全局外部指针变量在 DLL 中不可见
- 在没有外部文件的情况下在应用会话之间保存变量
- 外部变量的初始化
- 全局变量的循环依赖性与外部说明符
- 如何在命名空间中初始化外部变量
- 声明类指针变量外部班级
- 在 VC++ 中访问一个文件中声明的变量.(外部关键字用法)
- 为什么 cout 不打印变量"C"外部?
- 全局变量外部声明后的线程专用指令
- c++变量外部声明