C# 嵌套for循环处的变量
我有一个关于for循环的问题; 代码如下C# 嵌套for循环处的变量,c#,loops,for-loop,C#,Loops,For Loop,我有一个关于for循环的问题; 代码如下 for (int i = 0; i <= 3; i++) { for (int j = 0; j < 2; j++) { Console.WriteLine("J"); } Console.WriteLine("I"); } 对于(int i=0;i您的代
for (int i = 0; i <= 3; i++)
{
for (int j = 0; j < 2; j++)
{
Console.WriteLine("J");
}
Console.WriteLine("I");
}
对于(int i=0;i您的代码,在外部循环结束第一次迭代后,它将继续并重新执行内部循环。但重新执行意味着重新初始化索引器变量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");
}
}
void Main()
{
Test1();
Test2();
TestWithWhile();
}
void Test1()
{
对于(int i=0;i,因为内部循环被重新初始化,并以j=0开始。为什么?我不理解这背后的逻辑。我读了很多关于for循环的内容,但仍然没有得到嵌套的内容。外部for完成第一个循环后,它会重新启动内部循环。但重新启动意味着重新初始化所有内容。另外,命令ts j=0非常感谢Steve!我更了解循环背后的逻辑。感谢您的关注
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
}
}