C++與演算法

跳出迴圈 break

有時候我們會希望在迴圈執行到一半的時候就離開迴圈,而不要等到做完一次迴圈裡的所有事情。

英文加油站

  • break:中斷、休息


語法

  • 當滿足中斷條件時,就離開迴圈( while 或 for )
while / for( ... )
{
    ...
    if( 中斷條件 )
    {
        break;
    }
    ...
}



範例1 - 離開while

  • 以下範例中while迴圈重複的條件是1,在沒有中斷的情況下,會永遠執行下去。
  • 透過break,可以強行跳出while

code

#include<iostream>
using namespace std;

int main()
{
    int i = 0;
    while( 1 )
    {
        cout << i << endl;
        if( i>10 )
        {
            break;
        }

        i = i+1;
    }
    return 0;
}

output

0
1
2
3
4
5
6
7
8
9
10
11



範例2 - 存錢計畫

玫鉗小姐一直想要買價值十萬元的LV包包,但是她又懶得規劃存錢計畫。

所以她決定把每月的結餘都輸入進程式裡,程式會不斷幫她累計已經存了多少錢,一旦程式發現她的錢已經足以買LV包包,就會立刻提醒她。

輸入說明

每一列:一個整數,代表這個月可以存多少錢。

輸出說明

當發現可以買包包的瞬間,提醒玫鉗小姐,並且結束程式。

code

#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;
}

input

20000
30000
60000

output

total money :20000
total money :50000
total money :110000
You CAN buy it!