有時候我們會希望在迴圈執行到一半的時候就離開迴圈,而不要等到做完一次迴圈裡的所有事情。
while / for( ... )
{
...
if( 中斷條件 )
{
break;
}
...
}
1
,在沒有中斷的情況下,會永遠執行下去。#include<iostream>
using namespace std;
int main()
{
int i = 0;
while( 1 )
{
cout << i << endl;
if( i>10 )
{
break;
}
i = i+1;
}
return 0;
}
0
1
2
3
4
5
6
7
8
9
10
11
玫鉗小姐一直想要買價值十萬元的LV包包,但是她又懶得規劃存錢計畫。
所以她決定把每月的結餘都輸入進程式裡,程式會不斷幫她累計已經存了多少錢,一旦程式發現她的錢已經足以買LV包包,就會立刻提醒她。
每一列:一個整數,代表這個月可以存多少錢。
當發現可以買包包的瞬間,提醒玫鉗小姐,並且結束程式。
#include<iostream>
using namespace std;
int main()
{
int total_money;
int month_money;
total_money = 0;
while( cin >> month_money )
{
total_money = total_money + month_money;
cout << "total money :" << total_money << endl;
if( total_money >= 100000 )
{
break;
}
}
cout << "You CAN buy it!" << endl;
return 0;
}
20000
30000
60000
total money :20000
total money :50000
total money :110000
You CAN buy it!