C++中do while循环的使用细节
前面已经学习了 for 循环和 while 循环。第3种 C++循环是 do while,它不同于另外两种循环,因为它是出口条件(exit condition)循环。这意味着这种循环将首先执行循环体,然后再判定测试表达式,决定是否应继续执行循环。如果条件为false,则循环终止:否则,进入新一轮的执行和测试。这样的循环通常至少执行一次,因为其程序流必须经过循环体后才能到达测试条件。下面是其句法:
do
body
while(test-expression);
循环体是一条语句或用括号括起的语句块。图5.4总结了do while 循环的程序流程。
通常,入口条件循环比出口条件循环好,因为入口条件循环在循环开始之前对条件进行检查。例如,假设程序清单 5.13 使用 do while(而不是 while),则循环将打印空值字符及其编码,然后才发现已到达字符串结尾。但是有时 do while 测试更合理。例如,请求用户输入时,程序必须先获得输入,然后对它进行测试。程序清单 5.15 演示了如何在这种情况下使用 do while。
// dowhile.cpp -- exit-condition loop
#include <iostream>
int main()
{
using namespace std;
int n;
cout << "Enter numbers in the range 1-10 to find ";
cout << "my favorite number\n";
do
{
cin >> n; // execute body
} while (n != 7); // then test
cout << "Yes, 7 is my favorite.\n" ;
// cin.get();
// cin.get();
return 0;
}
下面是该程序的运行情况:
Enter numbers in the range 1-10 to find my favorite number
9
4
7
Yes,7 is my favorite.
对C++感兴趣的朋友点这里:C/C++课程