int count = 1; while (count <= 10) { cout << count << endl; count++; if (count == 6) break; }这个例子只是为了说明在循环中的 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.
for (row = 0; row < 3; row++) { for (star = 0; star < 20; star++) { cout << '*'; if (star == 10) break; } cout << endl; }该程序段的输出结果如下:
***********
***********
***********
int testVal = 0; while (testVal < 10) { testVal++; if (testVal) == 4 continue; //终止循环的该次迭代 cout << testVal << " "; }这个循环看起来像是要显示整数 1?10。但是,其实际输出如下:
1 2 3 5 6 7 8 9 10
请注意,数字未不打印。这是因为当 testVal 等于 4 时,continue 语句会导致循环跳过 cout 语句并开始下一次迭代。#include <iostream> #include <iomanip> using namespace std; int main() { int numDVDs; // Number of DVDs being rented double total = 0.0; // Accumulates total charges for all DVDs char current; // Current release? (Y/N) // Get number of DVDs rented cout << "How many DVDs are being rented?"; cin >> numDVDs; //Determine the charges for (int dvdCount = 1; dvdCount <= numDVDs; dvdCount++) { if (dvdCount % 3 == 0)// If it's a 3rd DVD itT s free { cout <<" DVD #" << dvdCount << " is free! \n"; continue; } cout << "Is DVD #" << dvdCount << " a current release (Y/N) ? "; cin » current; if ( (current == 'Y') || (current == 'y')) total += 3.50; else total += 2.50; } //Display the total charges cout << fixed << showpoint << setprecision(2); cout << "The total is $" << total << endl; return 0; }程序输出结果:
How many DVDs are being rented? 6
Is DVD #1 a current release (Y/N) ? y
Is DVD #2 a current release (Y/N) ? n
DVD #3 is free!
Is DVD #4 a current release (Y/N)? n
Is DVD #5 a current release (Y/N)? y
DVD #6 is free!
The total is $12.00
Copyright © 广州京杭网络科技有限公司 2005-2024 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有