// do 循环执行
do
{
cout << "a 的值:" << a << endl;
a = a + 1;
if( a > 15)
{
// 终止循环
break;
}
}while( a < 20 );
return 0;
}
当上面的代码被编译和执行时,它会产生下列结果:
a 的值: 10
a 的值: 11
a 的值: 12
a 的值: 13
a 的值: 14
a 的值: 15
用于 switch 中的 break 语句也可以放在循环中,当遇到 break 时,循环立即停止,程序跳转到循环后面的语句。
以下是一个带有 break 语句的循环示例。程序段中的 while 循环看起来要执行 10 次,但 break 语句导致它在第 5 次迭代后即停止:
int count = 1;
while (count <= 10)
{
cout << count << endl;
count++;
if (count == 6)
break;
}
这个例子只是为了说明在循环中的 break 语句的作用。通常不会有人以这种方式来使用它,因为它违反了结构化编程的规则,并使代码难以理解、调试和维护。
一个循环的退出应该通过循环顶部的条件测试来控制,就像在 while 循环或 for 循环中那样,或者在底部,就像在 do-while 循环中那样。通常在循环中使用 break 语句的唯一时间是在发生错误的情况下提前退出循环。下面的程序提供了这样一个示例:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double number;
cout << "Enter 5 positive numbers separated by spaces and \n" << "I will find their square roots: ";
for (int count = 1; count <= 5; count++)
{
cin >> number;
if (number >= 0.0)
{
cout << "\nThe square root of " << number << " is " << sqrt(number) <<endl;
}
else
{
cout << number << " is negative. " << "I cannot find the square root of a negative number. The program is terminating.\n";
break;
}
}
return 0;
}
程序输出结果:
Enter 5 positive numbers separated by spaces and I will find their square roots: 12 15 -17 19 31
The square root of 12 is 3.4641
The square root of 15 is 3.87298
-17 is negative. I cannot find the square root of a negative number. The program is terminating.