我有一个关于 for 循环的问题; 代码如下
for (int i = 0; i <= 3; i++)
{
for (int j = 0; j < 2; j++)
{
Console.WriteLine("J");
}
Console.WriteLine("I");
}
这段代码的输出是;
J J I J J I J J I J J I
我的问题是:首先 for 循环“i”为 0 且条件为真,因此循环进入第二个循环 j 为 0 且条件为真。它写入“J”,然后 j++ 正在工作,现在 J 为 1。第二个循环再次写入“J”,然后将其增加到 2,因此第二个 for 循环条件为假,然后转到第一个 for 循环,它写入“I”然后增加第一个循环 i 现在是 1 所以第一个 for 循环条件为真,然后进入第二个:问题从这里开始。 J 是 2,J 是如何在第一个循环条件再次为真后变为 0 并再次写入 2 J 的?
我希望我能正确地告诉你我的问题。 非常感谢
答案 0 :(得分:1)
您的代码,在外部循环结束第一次迭代后,它继续并重新执行内部循环。但是重新执行意味着用 j=0 重新初始化索引器变量,因此它再次打印值“J”的两倍
您可以在这两个示例中看到不同之处。第一个是您当前的代码,第二个是不重新初始化 j 变量
void Main()
{
Test1();
Test2();
TestWithWhile();
}
void Test1()
{
for (int i = 0; i <= 3; i++)
{
// At the for entry point the variable j is declared and is initialized to 0
for (int j = 0; j < 2; j++)
{
Console.Write("J");
}
// At this point j doesn't exist anymore
Console.WriteLine("I");
}
}
void Test2()
{
// declare j outside of any loop.
int j = 0;
for (int i = 0; i <= 3; i++)
{
// do not touch the current value of j, just test if it is less than 2
for (; j < 2; j++)
{
Console.Write("J");
}
// After the first loop over i the variable j is 2 and is not destroyed, so it retains its exit for value of 2
Console.WriteLine("I");
}
}
最后,第三个示例展示了使用两个嵌套的 while 循环来模拟应用在代码中的 for 循环的相同逻辑。在这里您可以看到导致变量 j 重新初始化的流程
void TestWithWhile()
{
int i = 0; // this is the first for-loop initialization
while (i <= 3) // this is the first for-loop exit condition
{
int j = 0; // this is the inner for-loop initialization
while (j < 2) // this is the inner for-loop exit condition
{
Console.Write("J");
j++; // this is the inner for-loop increment
}
Console.WriteLine("I");
i++; // this is the first for-loop increment
}
}