C++嵌套循环,外部有变量

C++ nested loops with variables outside

本文关键字:变量 外部 嵌套循环 C++      更新时间:2023-10-16

这绝对是一个愚蠢的问题,已经回答了多次,但我真的很困惑,找不到如何谷歌。
我有大约 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上。 在第一次迭代中(当x12时),你会得到打印的结果,即

2 : 2
2 : 3
2 : 4
2 : 5

由于您尚未重新初始化y2变量,因此,在内部循环的所有后续迭代中,条件y1 <= y2的计算结果为false(此时在本例中y26)。因此,您没有按预期获得输出。

您可以通过以下修改后的代码来确认这一点:

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;
}
}