在 do-while 循环和 if else 语句中,在语句末尾更改变量值并使用它来创建 while bool 表达式最有好处,还是最好设置 while 表达式始终为真,然后在 if else 语句中使用 break 语句。
为了澄清,这里有两种方法。
do
{
cout << "What is your choice?" << endl;
cin >> choice;
if(choice == 1)
{
cout << "You chose 1" << endl;
doWhileModifier = 1;
} else {
cout << "That's not a correct choice" << endl;
doWhileModifier = 0;
}
}
while (doWhileModifier == 0);
对比
do
{
cout << "What is your choice?" << endl;
cin >> choice;
if(choice == 1)
{
cout << "You chose 1" << endl;
break;
} else {
cout << "That's not a correct choice" << endl;
}
}
while (true);
我最初是用第一种方式做的,但现在我倾向于第二种方式。
非常感谢输入!
最佳答案
两个 do-while 循环都能完成工作,因此您可以根据个人喜好在代码中使用哪个 do-while 循环。但是如果你比我更喜欢第二个,我会建议你只做一个 while 循环而不是一个 do-while 循环,因为它更简单,更容易阅读,而且它做的事情和 do-while 循环一样。
关于c++ - do-while 循环的哪个例子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32917688/