C#While循环与For循环? [英] C# While Loop vs For Loop?

查看:67
本文介绍了C#While循环与For循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,一个问题一直困扰着我一段时间,而While和For循环之间的实际主要区别是什么.纯粹是可读性吗?您可以在for循环中完成的所有基本工作都可以在while循环中完成,只是在不同的地方.因此,请考虑以下示例:

In C# a question has been bugging me for a while and its what is that actual major difference between a While and For Loop. Is it just purely readability ie; everything you can essentially do in a for loop can be done in a while loop , just in different places. So take these examples:

int num = 3;
while (num < 10)
{
    Console.WriteLine(num);
    num++;
} 

vs

for (int x = 3; x < 10; x++)
{
    Console.WriteLine(x);
}

两个代码循环都产生相同的结果,这是for循环迫使您声明一个新变量并在每个循环循环开始时设置迭代值的唯一区别吗?也许我在主要差异方面缺少其他东西,但是如果有人可以让我直截了当,那会很好.谢谢.

Both code loops produce the same outcome and 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? Maybe I'm missing something else in terms of any major differences but it would good if someone can set me straight regarding this. Thanks.

推荐答案

是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个元素中的任何一个.最小形式是

The for loop forces you to nothing. You can omit any of the 3 elements. The smallest form is

for(;;)  // forever
{
  DoSomething();
}

但是您可以使用这三个元素来编写更简洁的代码:

But you can use the 3 elements to write more concise code:

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循环中是本地的.一个明显的好处.

Note the outer {} braces, in for(int i = 0; ...; ...) the i is local to the for-loop. A clear benefit.

但是用法的主要区别是在循环内调用continue;时,在while循环中比在for循环中更容易出错.

But the major difference in usage is when you call continue; inside the loop, much easier to get the logic wrong in a while-loop than in a for-loop.

这篇关于C#While循环与For循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆