發車時刻表

題目一:巴士發車時刻表

h、m:表開始發車的時與分

step:表發車間隔

*迴圈解法:

#include <iostream>
#include <iomanip>

using namespace std;
void main(){
    int count=1, h=6, m=20, step=40;
    for(; h < 24; m+= step, count++){        
        if (m >= 60) {
            h ++;
            m -= 60;
        }
        cout << setw(2) << h << ":" << setw(2) << m << " ";
        if (count %4 ==0) cout << endl;
    } 
    system("pause");
}

*遞回解法:

#include <iostream>
#include <iomanip>

using namespace std;
void loop(int count, int h, int m, int step){
    cout << setw(2) << h << ":" << setw(2) << m << " ";
    if (count %4 ==0) cout << endl;
    m+=step; count++;
    if (m >= 60) {
        h ++;
        m -= 60;
    }
    if (h < 24) loop(count, h, m, step);
}

void main(){
    int count=1, h=6, m=20, step=40;
    loop(count, h,m, step);    
    cout << endl;
    system("pause");
}

results matching ""

    No results matching ""