设为首页 加入收藏

TOP

3.2.2 for循环的变体(3)
2013-10-07 16:07:16 来源: 作者: 【 】 浏览:59
Tags:3.2.2 for 循环 变体

3.2.2  for循环的变体(3)

执行循环内部的continue语句将跳过循环体中其他剩余的语句,而立即启动下一次循环迭代。可以用下面的代码来示范continue语句的作用:
 

  1. #include <iostream> 
  2. using std::cin;  
  3. using std::cout;  
  4. using std::endl;  
  5. int main()  
  6. {  
  7. int value(0), product(1);  
  8. for(int i = 1; i <= 10; i++)  
  9. {  
  10. cout << "Enter an integer: ";  
  11. cin >> value;  
  12. if(0 == value)                    // If value is zero  
  13. continue;                      // skip to next iteration  
  14. product *= value;  
  15. }  
  16. cout << "Product (ignoring zeros): " << product 
  17. << endl;  
  18. return 0;                               // Exit from loop  
  19. }  

该循环读取10个数值,目的是得到输入值的乘积。if语句检查每个输入值,如果是0,则continue语句跳到下一次迭代。这样,即使某个输入值为0,也不会得到等于0的乘积。显然,如果最后一次迭代时输入值为0,则该循环将结束。当然还有其他一些方法可以得到相同的结果,但continue语句提供了非常有用的功能,特别是在需要从循环体的不同位置跳到当前迭代结束处这样的复杂循环中。

在for循环的逻辑中,break和continue语句的作用如图3-4所示。

显然,在实际情况中将在某些条件测试逻辑中使用break和continue语句,以确定何时应该退出循环,或者何时应该跳过循环的迭代。还可以在本章稍后讨论的其他类型循环中使用break和continue语句,它们还是以完全相同的方式工作。

图  3-4  循环中的break和continue语句

试一试:在循环中使用其他数据类型

迄今为止,我们仅仅使用过整数来记录循环的迭代次数。在使用何种变量类型来记录循环迭代次数方面,绝对不会受到任何限制。请看下面的示例:

  1. // Ex3_11.cpp  
  2. // Display ASCII codes for alphabetic characters  
  3. #include <iostream> 
  4. #include <iomanip> 
  5. using std::cout;  
  6. using std::endl;  
  7. using std::hex;  
  8. using std::dec;  
  9. using std::setw;  
  10. int main()  
  11. {  
  12. for(char capital = 'A'small = 'a'; capital <= 'Z'; capital++, small++)  
  13. cout << endl 
  14. << "\t" << capital                                                              // Output capital as a character  
  15. << hex << setw(10) << static_cast <int> (capital) // and as hexadecimal  
  16. << dec << setw(10) << static_cast <int> (capital) // and as decimal  
  17. << " " << small                                                                         // Output small as a character  
  18. << hex << setw(10) << static_cast <int> (small) // and as hexadecimal  
  19. << dec << setw(10) << static_cast <int> (small); // and as decimal  
  20. cout << endl;  
  21. return 0;  
  22. }  

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

评论

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

·用 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)