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开始一直到输入number(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);
}
}
}
有人可以帮我理解吗?
不同之处在于,在第二个循环中,您将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++;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句