在 C# 中,有一个问题困扰了我一段时间,即 While 循环和 For 循环之间的实际主要区别是什么。仅仅是纯粹的可读性吗?你基本上可以在 for 循环中做的所有事情都可以在 while 循环中完成,只是在不同的地方。所以举这些例子:
int num = 3;
while (num < 10)
{
Console.WriteLine(num);
num++;
}
对比
for (int x = 3; x < 10; x++)
{
Console.WriteLine(x);
}
两个代码循环产生相同的结果,两者之间的唯一区别是 for 循环强制您声明一个新变量并在每个循环周期开始时设置迭代值吗?也许我在任何主要差异方面都遗漏了其他一些东西,但如果有人可以让我直截了当,那就太好了。谢谢。
最佳答案
is the only difference between the two that the for loop forces you to declare a new variable and also set the iteration value each loop cycle at the start?
for 循环迫使你什么都不做。您可以省略这 3 个元素中的任何一个。最小的形式是
for(;;) // forever
{
DoSomething();
}
但是您可以使用这 3 个元素来编写更简洁的代码:
for(initializer; loop-condition; update-expression)
{
controlled-statements;
}
相当于:
{
initializer;
while(loop-condition)
{
controlled-statements;
continue_target: // goto here to emulate continue
update-expression;
}
}
注意外部 {}
大括号,在 for(int i = 0; ...; ...)
中 i
是局部于 for 循环。 一个明显的好处。
但用法上的主要区别在于当您在循环内调用 continue;
时,在 while 循环中比在 for 循环中更容易弄错逻辑。
关于C# While 循环与 For 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35395800/