当使用for循环比while循环? [英] When to use the for loop over the while loop?

查看:146
本文介绍了当使用for循环比while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以使用循环和while循环相同的目的。
在拿什么它们影响我们的code如果我用,而不是一会儿吗?同样的问题出现的if-else和开关外壳之间?如何决定使用什么样的?
例如哪一个,你会preFER?

We can use for loop and while loop for same purpose. in what means they effect our code if I use for instead of while? same question arises between if-else and switch-case? how to decide what to use? for example which one you would prefer?

这code:

int main()
{
   int n = 10;

   for(int i=0;i<n;i++)
    {
        do_something();
    }
    return 0;
}

还是这个code:

Or this code:

int main()
{
    int n=10,i=0;

    while(i<n)
    {
          do_something();
          i++;
    }
    return 0;
}

如果使用或while循环不以任何方式影响了code,那么我可能知道什么是需要做出同样的问题2溶液?

if using for or while loop does not effect the code by any means then may I know What was the need to make 2 solution for same problem?

推荐答案

如果您知道迭代循环应事先运行数量,我会建议在结构。虽然循环是好当循环的终止条件发生在一些还没有到确定时间。

If you know the number of iterations the loop should run beforehand, I would recommend the for construct. While loops are good for when the loop's terminating condition happens at some yet-to-be determined time.

这篇关于当使用for循环比while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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