do {
...
} while (true);
这个例子中的
true
是什么意思?
示例:
do {
cout << " 1-basic arithmetic operations " << endl;
cout << " 2-summation " << endl;
cout << " 3-Exit " <<endl;
cout << "Enter your choice: " << endl;
cin >> main_choice;
switch(main_choice){
case 1:
operation();
break;
case 2:
summation();
break;
case 3:
cout << "Exiting program. Goodbye!" << endl;
return 0;
default:
cout << "Invalid choice. Please try again." << endl;
}
} while (true);
使用 do-while 结构时,可以使用以下语法:
do{
<body>
} while(<condition>)
这里,
<condition>
代表一个布尔表达式,意味着它可以计算为 true 或 false。如果条件为真,则执行<body>
内的指令,并继续循环。如果条件为假,则循环终止,程序继续执行循环体之外的指令。
使用 do-while 构造,您总是在评估条件之前执行
<body>
一次。
如果
<condition>
为 true,则您正在编写无限循环。