我希望有人解释一下 C++ 中的 while 和 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 循环是一个入口控制循环,即它首先检查条件 在 while(condition){ ...body... }
中,然后执行循环体并不断循环和重复该过程直到条件是假的.
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 while 循环是一个退出控制循环,即它检查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 while 语句被打印的情况下,因为它现在对条件一无所知,直到它至少执行一次主体,然后因为条件失败而停止.
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 和 do while 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!