【问题标题】:What is causing the difference in these two loops?是什么导致这两个循环的差异?
【发布时间】:2021-04-03 19:31:23
【问题描述】:
static void Main(string[] args)
{
    int num = Convert.ToInt32(Console.ReadLine());
    int res = 1;
    while (res <= num)
    {
        res++;
        if ((res % 2) == 0)
        {
            Console.WriteLine(res);
        }
    }
}

我使用 int 8、10 和 5 作为我的控制组,这些应该只输出从 1 开始的偶数,直到输入数字 (8,10,5)。

static void Main(string[] args)
{
    int num = Convert.ToInt32(Console.ReadLine());
    for (int res = 1; res <= num; res++)
    {
        if ((res % 2) == 0)
        {
            Console.WriteLine(res);
        }
    }
}

谁能帮我理解一下?

【问题讨论】:

  • 您看到的区别是什么?
  • @Enigmativity 主要是奇数,while循环给我数字6,它应该停在4。
  • 您应该在问题中包含该详细信息。

标签: c# increment


【解决方案1】:

不同之处在于,在第二个循环中,您在每次迭代的最后递增 res(这就是 for 循环的工作方式),而在第一个循环中,您在检查“之前递增 res甚至”。

这意味着当res 为5 并且while 循环的新迭代开始时,res 首先递增到6,并且6 通过检查,导致打印6。然而,在 for 循环中,res 在 5 未通过偶数检查后递增。然后迭代停止,因为 6 现在大于 5。

要使 while 循环与 for 循环相同,请将 res++ 移到末尾:

while (res <= num)
{
    if ((res % 2) == 0)
    {
        Console.WriteLine(res);
    }
    res++;
}

【讨论】:

  • 谢谢你的详细解释,你能解释一下如何使while循环输出与for循环相同吗?
  • 哇哦...我真的需要更好地理解代码结构。
【解决方案2】:

在第一个循环中,你增加变量res,然后检查它是否是偶数。

在第二个循环中检查它是否是事件,并在每次迭代结束时增加res 变量的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-11
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2021-05-27
    • 1970-01-01
    • 2010-10-29
    相关资源
    最近更新 更多