C ++和while之间的区别? [英] The difference between while and do while C++?

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

问题描述

我希望有人解释一下C ++中do和while之间的区别

I would like someone to explain the difference between a while and a do while in C++

我刚刚开始学习C ++,并且使用此代码,我似乎得到了相同的输出:

I just started learning C++ and with this code I seem to get the same output:

int number =0;

while (number<10)
{
cout << number << endl;
number++
}

和此代码:

int number=0;

do
{
cout << number << endl;
number++
} while (number<10);

这两个计算中的输出都相同.因此似乎没有区别. 我试图寻找其他示例,但是它们看起来很难理解,因为其中包含了数学知识和其他我还没有学到的东西.另外,我的书对我的问题给出了一种迷幻的答案.

The output is both the same in these both calculations. So there seem to be no difference. I tried to look for other examples but they looked way to difficult to understand since it contained mathemetical stuff and other things which I haven't quite learned yet. Also my book gives a sort of psychedelic answer to my question.

有没有更简单的示例来显示这两个循环之间的区别?

Is there an easier example to show the difference between these 2 loops?

我很好奇

推荐答案

while 循环是进入控制循环,即它首先检查条件和中的/em>,然后执行循环主体,并继续循环并重复该过程,直到条件为假.

The while loop is an entry control loop, i.e. it first checks the condition in the while(condition){ ...body... } and then executes the body of the loop and keep looping and repeating the procedure until the condition is false.

执行时循环是退出控制循环,即,它检查正文后do{...body...}while(condition) 中的状况循环已执行( do while循环中的主体将始终至少执行一次 ),然后再次循环遍历主体,直到出现条件被发现是错误的.

The do while loop is an exit control loop, i.e. it checks the condition in the do{...body...}while(condition) after the body of the loop has been executed (the body in the do while loop will always be executed at least once) and then loops through the body again until the condition is found to be false.

希望这会有所帮助:)

例如: 在while循环的情况下,如果1不小于1,则不会打印任何内容,条件失败并且循环退出

For Example: In case of while loop nothing gets printed in this situation as 1 is not less than 1, condition fails and loop exits

int n=1;
while(n<1)
    cout << "This does not get printed" << endl;

在执行do语句的情况下,因为它现在对条件一无所知,直到它至少执行一次主体,然后由于条件失败而停止,这才是

Whereas in case of do while the statement gets printed as it doesn't know anything about the condition right now until it executes the body atleast once and then it stop because condition fails.

int n=1;
do
   cout << "This one gets printed" << endl;
while(n<1);

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

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