设为首页 加入收藏

TOP

3.2.3 while循环
2013-10-07 16:07:08 来源: 作者: 【 】 浏览:70
Tags:3.2.3 while 循环

3.2.3  while循环

C++(www.cppentry.com)中第二种循环是while循环。for循环主要用来以指定的迭代次数重复执行某条语句或某个语句块,而while循环用来在指定条件为true时执行某条语句或某个语句块。while循环的通用形式如下:

  1. while(condition)  
  2. loop_statement; 

只要condition表达式的值为true,就重复执行loop_statement。当条件变为false之后,程序继续执行循环后面的语句。和往常一样,可以用大括号之间的语句块来取代单个的loop_statement。

while循环的逻辑可以用图3-5来表示。

试一试:使用while循环

可以使用while循环来重写前面计算平均值的示例(Ex3_10.cpp)。
 

  1. // Ex3_12.cpp  
  2. // Using a while loop to compute an average  
  3. #include <iostream> 
  4. using std::cin;  
  5. using std::cout;  
  6. using std::endl;  
  7. int main()  
  8. {  
  9. double value(0.0);                 // Value entered stored here  
  10. double sum(0.0);                   // Total of values accumulated here  
  11. int i(0);                            // Count of number of values  
  12. char indicator('y');              // Continue or not  
  13. while('y' == indicator )         // Loop as long as y is entered  
  14. {  
  15. cout << endl 
  16. << "Enter a value: ";  
  17. cin >> value;                  // Read a value  
  18. ++i;                             // Increment count  
  19. sum += value;                  // Add current input to total  
  20. cout << endl 
  21. << "Do you want to enter another value (enter y or n)  ";  
  22. cin >> indicator; // Read indicator  
  23. }  
  24. cout << endl 
  25. << "The average of the " << i 
  26. << " values you entered is " << sum/i << "."  
  27. << endl;  
  28. return 0;  
  29. }  

示例说明

对于相同的输入,上面的程序产生与以前相同的输出。该程序更新了一条语句,另外添加了一条语句。上面的代码突出显示了这两条语句。while语句代替了for循环语句,同时删除了在if语句中对indicator的测试,因为该功能现在由while条件完成。我们必须用y代替先前的n来初始化indicator,否则while循环将立即终止。只要while中的条件返回true,该循环就继续。

可以将任何结果为true或false的表达式用作while循环的条件。如果上面的循环条件扩展为允许输入'Y'及'y'来使循环继续,则该示例将成为更好的一个程序。我们可以将while条件修改成下面的样子,以实现这样的功能。
 

  1. while(('y' == indicator) || ('Y' == indicator)) 

使用始终为true的条件,还可以建立无限期执行的while循环。这样的循环可以写成下面的形式:
 

  1. while(true)  
  2. {  
  3. ...  
  4. }  

也可以用整数值1作为循环控制表达式,1将转换为bool值true。当然,这里的要求与无穷for循环的情形相同:必须在循环块内提供一种退出循环的方法。第4章将介绍其他使用while循环的方式。
 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇3.2.2 for循环的变体(5) 下一篇3.2.4 do-while循环

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·用 C 语言或者限制使 (2025-12-25 08:50:05)
·C++构造shared_ptr为 (2025-12-25 08:50:01)
·既然引用计数在做 GC (2025-12-25 08:49:59)
·Java 编程和 c 语言 (2025-12-25 08:19:48)
·. net内存管理宝典这 (2025-12-25 08:19:46)