这是do-while循环的例子

Which example for a do-while loop?

本文关键字:循环 do-while 这是      更新时间:2023-10-16

在do-while循环和if else语句中,在语句结束时更改变量值并使用该值来创建while布尔表达式是否符合最佳利益,或者最好将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循环是一样的。