【问题标题】:Variable at Nested for loop嵌套 for 循环中的变量
【发布时间】:2021-02-20 14:40:31
【问题描述】:

我有一个关于 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 是如何实现的?

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

【问题讨论】:

  • 因为内部循环被重新初始化并且以 j=0 开头。
  • 为什么?我不明白这背后的逻辑。我阅读了很多关于 for 循环的内容,但仍然没有找到嵌套的内容。
  • 在外部 for 完成第一个循环后,它再次重新启动内部循环。但是重新启动意味着重新初始化所有内容。还有设置 j=0 的命令

标签: c# loops for-loop


【解决方案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
    }
}

【讨论】:

  • 非常感谢史蒂夫!我更好地理解 for 循环背后的逻辑。感谢您的关注
猜你喜欢
  • 1970-01-01
  • 2018-12-25
  • 1970-01-01
  • 2011-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-10
  • 1970-01-01
相关资源
最近更新 更多