3.2.3 while循环
C++(www.cppentry.com)中第二种循环是while循环。for循环主要用来以指定的迭代次数重复执行某条语句或某个语句块,而while循环用来在指定条件为true时执行某条语句或某个语句块。while循环的通用形式如下:
- while(condition)
- loop_statement;
只要condition表达式的值为true,就重复执行loop_statement。当条件变为false之后,程序继续执行循环后面的语句。和往常一样,可以用大括号之间的语句块来取代单个的loop_statement。
while循环的逻辑可以用图3-5来表示。

试一试:使用while循环
可以使用while循环来重写前面计算平均值的示例(Ex3_10.cpp)。
- // Ex3_12.cpp
- // Using a while loop to compute an average
- #include <iostream>
- using std::cin;
- using std::cout;
- using std::endl;
- int main()
- {
- double value(0.0); // Value entered stored here
- double sum(0.0); // Total of values accumulated here
- int i(0); // Count of number of values
- char indicator('y'); // Continue or not
- while('y' == indicator ) // Loop as long as y is entered
- {
- cout << endl
- << "Enter a value: ";
- cin >> value; // Read a value
- ++i; // Increment count
- sum += value; // Add current input to total
- cout << endl
- << "Do you want to enter another value (enter y or n) ";
- cin >> indicator; // Read indicator
- }
- cout << endl
- << "The average of the " << i
- << " values you entered is " << sum/i << "."
- << endl;
- return 0;
- }
示例说明
对于相同的输入,上面的程序产生与以前相同的输出。该程序更新了一条语句,另外添加了一条语句。上面的代码突出显示了这两条语句。while语句代替了for循环语句,同时删除了在if语句中对indicator的测试,因为该功能现在由while条件完成。我们必须用y代替先前的n来初始化indicator,否则while循环将立即终止。只要while中的条件返回true,该循环就继续。
可以将任何结果为true或false的表达式用作while循环的条件。如果上面的循环条件扩展为允许输入'Y'及'y'来使循环继续,则该示例将成为更好的一个程序。我们可以将while条件修改成下面的样子,以实现这样的功能。
- while(('y' == indicator) || ('Y' == indicator))
使用始终为true的条件,还可以建立无限期执行的while循环。这样的循环可以写成下面的形式:
- while(true)
- {
- ...
- }
也可以用整数值1作为循环控制表达式,1将转换为bool值true。当然,这里的要求与无穷for循环的情形相同:必须在循环块内提供一种退出循环的方法。第4章将介绍其他使用while循环的方式。