何时使用 while 循环而不是 for 循环

2022-09-04 23:44:47

我也在学习java和android。几乎所有我们可以执行的事情,同时循环我们可以在循环中做的事情。

我发现一个简单的条件,其中使用 while 循环比 for 循环更好

如果我必须在我的程序中使用计数器的值,那么我认为虽然循环比for循环更好

使用 while 循环

int counter = 0;
while (counter < 10) {
    //do some task
    if(some condition){
        break;
    }
}
useTheCounter(counter); // method which use that value of counter do some other task

在这种情况下,我发现 while 循环比 for 循环更好,因为如果我想在 for 循环中实现相同的值,我必须将计数器的值分配给另一个变量。

但是,当 while 循环优于 for 循环时,是否存在任何特定情况


答案 1

一个主要的区别是,当您事先不知道需要执行的迭代次数时,循环最适合。如果您在进入循环之前知道这一点,则可以使用循环。whilefor


答案 2

循环只是一种特殊的 while 循环,它恰好处理变量递增。您可以使用任何语言模拟具有循环的循环。它只是句法糖(除了python,实际上就是)。所以不,没有特定的情况,一个比另一个好(尽管出于可读性的原因,当你做简单的增量循环时,你应该更喜欢循环,因为大多数人都可以很容易地分辨出发生了什么)。forforwhileforforeachfor

for 可以表现得像同时:

while(true)
{
}

for(;;)
{
}

虽然可以表现得像:

int x = 0;
while(x < 10)
{
    x++;
}

for(x = 0; x < 10; x++)
{
}

在你的情况下,是的,你可以把它重写为一个for循环,如下所示:

int counter; // need to declare it here so useTheCounter can see it

for(counter = 0; counter < 10 && !some_condition; )
{
    //do some task
}

useTheCounter(counter);

推荐