首页 > 解决方案 > 嵌套 for 循环中的变量

问题描述

我有一个关于 for 循环的问题;代码如下

for (int i = 0; i <= 3; i++)
       {
           for (int j = 0; j < 2; j++)
           {
               Console.WriteLine("J");
           }

          Console.WriteLine("I");
        }

此代码的输出是;

JJIJJIJJIJJI

我的问题是:首先 for 循环“i”为 0,条件为真,所以循环进入第二个循环 j 为 0,条件为真。它写入“J”,然后 j++ 正在工作,现在 J 为 1。第二个循环再次写入“J”,然后将其增加到 2,因此第二个 for 循环条件为假,它进入第一个 for 循环,它写入“I”然后增加第一个循环 i 现在是 1 所以第一个 for 循环条件为真,然后它进入第二个:问题从这里开始。J 为 2,在第一个循环条件再次为真之后 J 变为 0 并再次写入 2 J 是如何实现的?

我希望我能正确地告诉你我的问题。太感谢了

标签: c#loopsfor-loop

解决方案


您的代码,在外部循环结束第一次迭代后,它会继续并重新执行内部循环。但是重新执行意味着重新初始化索引器变量 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
    }
}

推荐阅读