2014-02-27 54 views
0

在教科書中使用C++解決問題有一個問題,即您有一個可以在時間上前進24小時的時間機器,它希望您輸入開始時間結束時間使用小時值,分鐘值和表示時間是AM還是PM的布爾值,並計算出已經過了多少分鐘。我想用軍事時間來做這件事,而我能夠計算出開始時間是否少於結束時間(即0000和2359返回1439的時間)多少分鐘,但我無法弄清楚該怎麼做相反。C++時間機器不計算正確通過的時間量

這是我到目前爲止有:

#include <iostream> 
#include <cmath> 

using namespace std; 

int timeDifference(int t1, int t2) 
{ 
    int t1_mins = (t1/100) * 60 + (t1 % 100); 
    int t2_mins = (t2/100) * 60 + (t2 % 100); 
    return(t2_mins - t1_mins); 
} 

int main() 
{ 
    cout << "The time difference between 0000 and 2359 is " << 
     timeDifference(0,2359) << " minutes." << endl; 
    cout << "The time difference between 2359 and 0001 is " << 
     timeDifference(2359,1) << " minutes." << endl; 
    cout << "The time difference between 2010 and 1000 is " << 
     timeDifference(2010,1000) << " minutes." << endl; 
    cout << "The time difference between 0300 and 1500 is " << 
     timeDifference(300,1500) << " minutes." << endl; 
} 

任何幫助表示讚賞和感謝提前!

+0

那麼你有什麼希望它輸出爲'timeDifference(2359,1)'? 2? –

+0

@JosephMansfield是的,對於timeDifference(2010,1000)應該是830. – dsdouglous

+1

'std :: chrono :: duration'和'time_point'可能會使這個更清潔。 – David

回答

0

如果t2小於t1,只需將一整天的分鐘數加到t2。

這將導致下面的代碼:

#include <iostream> 
int timeDifference(int t1, int t2) 
{ 
    int t1_mins = (t1/100) * 60 + (t1 % 100); 
    int t2_mins = (t2/100) * 60 + (t2 % 100); 
    if (t2 < t1) 
     t2_mins += 24 * 60; 
    return(t2_mins - t1_mins); 
} 
0

std::chrono使事情變得更好......

鑑於24小時時間輸入持續時間:

using namespace std::chrono; 

minutes timeDifference(minutes t1, minutes t2) 
{ 
    if(t2 < t1) 
     t2 += 24h; 

    return t2 - t1; 
}