【问题标题】:C# for while loop bugC# for while 循环错误
【发布时间】:2021-05-20 22:10:00
【问题描述】:

如果我执行了这个,它会打印 hello world 16 次,然后卡在 while 语句中。

        bool avoiding_cone = true;
        for (int i = 0; i < 16; i++)
        {
            Console.WriteLine("Hello World!");
        } while (avoiding_cone) ;

如果 Avoid_cone 为 false,则打印 hello world 16 次并退出循环。

微软,能不能把这种行为改成更明智的做法?

更新:有人告诉我这是一个词法异常,确实是有道理的,因此不是错误。顺便说一句,我不想​​做任何具体的事情。我喜欢理解事情,而不是被告知不要担心,去做别的事情。

【问题讨论】:

  • 它们是 2 个独立的循环。一个 for 循环,然后是一个带有空语句的 while 循环。也许您正在考虑一个 do ... while 循环?

标签: loops for-loop while-loop


【解决方案1】:

这不是错误,你应该注意你的逻辑。 你想达到什么目的? while 循环看起来没有必要。

您可以将变量avoiding_cone 放入for 循环中。 例如:

bool avoiding_cone = true;
for (int i = 0; i < 16; i++)
{
     if(!avoiding_cone)
          Console.WriteLine("Hello World!");

      if(i == 3) avoiding_cone = false; //etc.. use any condition to change avoiding_code value
}

【讨论】:

  • 我只是想理解语言并指出可能存在错误。更多的是关于语言的目标是什么以及它是否有价值。
【解决方案2】:

我从来没有想过forwhile 可以这样使用。好吧,我想这不是一个错误,而是一个功能.. ;)

我会单独使用for,或者do { } while,我永远不会像这样使用forwhile,即使它是有效的。

【讨论】:

    【解决方案3】:

    有人告诉我这是词法异常,确实有道理,而且没有错误。

    我相信它相当于..

    bool avoiding_cone = false;
    for (int i = 0; i < 16; i++)
    {
        Console.WriteLine("Hello World!");
    }
    
    while (avoiding_cone);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-07
      相关资源
      最近更新 更多