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