while,dowhile和for循环之间的区别?哪个循环最好? [英] difference between while,dowhile and for loop? which loop is best?

查看:523
本文介绍了while,dowhile和for循环之间的区别?哪个循环最好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

while,dowhile和for循环之间的区别?哪个循环最好?

解决方案

它们都可以工作,但是您使用的循环将取决于您的要求. for将在已知序列上循环,而while将运行直到满足条件为止,而do-while始终运行一次.最好的选择是买书并做练习,以便您了解每种书的工作原理.

如果存在最佳"这样的情况,并且我们应该始终使用一种语言,那么该语言就不会打扰其他语言.

编辑是为了消除可笑的声称C ++不提供"while"的说法,该说法基于我6年前使用C ++的记忆,以及我的时差状态……


<我想使用某个循环来循环一个已知的编号,所以我喜欢使用for循环.的次数以及当我有要在每个循环中递增或递减的索引或指针时.它对于遍历字符串或数组很有用.

当您希望某些条件为真(即使无限期)为条件的循环时,和/或如果条件为false时根本不希望循环的东西,则while循环非常有用.这是因为测试条件是在循环开始时进行测试的.

一会儿与一会儿的不同之处在于,即使条件为假,它也会执行一次.这是因为条件是在循环结束时测试的.

当然,这取决于您希望代码执行的操作,因为每种代码都可以以各种方式使用. for循环可以没有增量或起始值,只能像一会儿一样运行.或者while循环可以使循环内的索引计数并最终进行测试.

并且不要忘记,您可以使用break和Continue语句. Break在任何时候都退出循环,并在循环中的任何语句之后继续跳转并继续循环.


difference between while,dowhile and for loop? which loop is best?

解决方案

They all work, but the one you use will depend on your requirements. for will loop over a known sequence, while will run until a condition is met, and do-while always runs once. Your best bet, is to buy a book and do exercises so you understand how each works.

If there was such a thing as ''best'', and we should always use one, the language would not bother to ofer the others.

Edited to remove the ludicrous claim that C++ does not offer ''while'', which was based on my memory of using C++ 6 years ago,and my state of jetlag......


I like using the for loop when I want something to loop a known no. of times and when I have indices or pointers that I want to increment or decrement with each loop. Its useful for going through strings or arrays.

A while loop is good for when you want something to loop as long as some condition is true, even indefinitely, and/or if you want something that won''t loop at all if the condition is false to start. This is because the test condition is tested at the begining of the loop.

A do while differs from the while in that it will execute once even if the condition is false to start with. This is because the condition is tested at the end of the loop.

Of course it depends on what you want the code to do as each of these can be used in various ways. A for loop can have no increments or starting values and just operate like a while. Or a while loop can have indices counting inside the loop that get tested at the end.

And don''t forget you can use break and continue statements. Break exits out of a loop at any point, and continue jumps over any statements after it in the loop and continues looping.


这篇关于while,dowhile和for循环之间的区别?哪个循环最好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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