C++中使用 do…while 循环
在有些情况(如程序清单 6.8 所示的情况)下,您需要将代码放在循环中,并确保它们至少执行一次。此时 do…while 循环可派上用场。
do…while 循环的语法如下:
do
{StatementBlock; // executed at least once
} while(condition); // ends loop if condition evaluates to false
注意到包含 while(expression)的代码行以分号结尾,这不同于前面介绍的 while 循环。在 while 循环中,如果包含 while(expression)的代码行以分号结尾,循环将就此结束,变成一条空语句。
除了外观形式,do-while 循环和 while 循环之间的区别是 do-while 是一个后测试循环,这意味着在循环结束时,也就是在每次迭代完成后,才测试其表达式。因此,即使测试表达式在开始时为 false,do-while 也至少要执行一次迭代。
以下程序演示了如何使用 do…while 循环来确保语句至少执行一次:
#include <iostream>
using namespace std;int main()
{char userSelection = 'x'; // initial valuedo{cout << "Enter the two integers: " << endl;int num1 = 0, num2 = 0;cin >> num1;cin >> num2;cout << num1 << " x " << num2 << " = " << num1 * num2 << endl;cout << num1 << " + " << num2 << " = " << num1 + num2 << endl;cout << "Press x to exit(x) or any other key to recalculate" << endl;cin >> userSelection;} while (userSelection != 'x');cout << "Goodbye!" << endl;return 0;
}
输出:
Enter the two integers:
654
-25
654 x -25 = -16350
654 + -25 = 629
Press x to exit(x) or any other key to recalculate
m
Enter the two integers:
909
101
909 x 101 = 91809
909 + 101 = 1010
Press x to exit(x) or any other key to recalculate
x
Goodbye!
分析:
这个程序的行为和输出与程序清单 6.8 很像。实际上,唯一的差别在于,第 6 行包含关键字 do,而第 18 行使用了 while。将按顺序执行每行代码,直到达到第 18 行的 while。到达第 18 行后, while 计算表达式 (userSelection != ‘x’)
的值。如果该表达式为 true,即用户没有按 x 退出,将重复执行循环。如果该表达式为 false,即用户按了 x 键,将退出循环,显示再见消息,并结束应用程序。
该文章会更新,欢迎大家批评指正。
推荐一个零声学院的C++服务器开发课程,个人觉得老师讲得不错,
分享给大家:Linux,Nginx,ZeroMQ,MySQL,Redis,
fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,
TCP/IP,协程,DPDK等技术内容
点击立即学习:C/C++后台高级服务器课程