2015-10-07 63 views
0

這是一個課程的任務,我幾乎把它放在了我想要的地方,只是希望得到一些關於繼續學習的最佳途徑的建議。C++時間轉換程序

用戶將以24小時格式輸入時間並以小時和分鐘輸入延遲時間。我必須在延遲結束時以AM/PM格式計算和顯示時間。我必須使用函數,並且不能使用全局變量。在小時部分輸入999時,我還需要退出條件。

基本上,我正在嘗試確定計算延遲的最佳方法。我嘗試了幾種不同的方法,但並沒有真正對他們中的任何一個感到滿意。現在,程序只需循環詢問幾小時,幾分鐘,然後延遲,直到我可以決定繼續進行的最佳方式。

#include <iostream> 

using namespace std; 

//Function Prototypes 
void convert(int&, int&, int&, char&); 
void output(int&, int&, char&); 

int main() 
{ 

    int hours, minutes, delay; 
    char ampm; 

    cout<<"Enter the value for Hours (999 to quit): "<<endl; 
    cin >> hours; 



    while (hours != 999) 
    { 
     cout << "Enter minutes: "; 
     cin >> minutes; 

     cout << "Enter delay: "; 
     cin >> delay; 

     cout<<"Enter the value for Hours (999 to quit): "<<endl; 
    cin >> hours; 


    } 
return 0; 
} 


void convert(int& hours, int& minutes, int& delay, char& ampm) 
{ 

    if(hours > 12) 
    { 
     hours = hours - 12; 
     ampm = 'p'; 
    } 
    else if(hours == 12) ampm = 'p'; 
    else ampm = 'a'; 
} 


void output(int& hours, int& minutes, char& ampm) 
{ 
    if(ampm == 'p') 
    { 
     (minutes < 10); cout << hours << ":0" << minutes << " P.M."; 
     cout << hours << ":" << minutes << " P.M."; 
    } 
    else 
    { 
     (minutes < 10); cout << hours << ":0" << minutes << " A.M."; 
     cout << hours << ":" << minutes << " A.M."; 
     } 

} 
+0

查找模運算符'%',它可能對您非常有用。 –

回答

0

我希望它有幫助。我試圖保持乾淨和簡單。

#include <iostream> 
#include <string> 
using namespace std; 

//Function Prototypes 
void convert(int&, int&, int&, string&); 
void output(int&, int&, string&); 

int main() 
{ 

    int hours, minutes, delay; 
    string ampm; 

    cout << "Enter hours(0-24): "; 
    cin >> hours; 

    do{ 
     cout << "Enter minutes: "; 
     cin >> minutes; 

     cout << "Enter delay(in minutes): "; 
     cin >> delay; 

     convert(hours, minutes, delay, ampm); 
     output(hours, minutes, ampm); 

     cout << endl << "Enter the value for Hours (999 to quit): "; 
     cin >> hours; 
    } while (hours != 999); 

    return 0; 
} 


void convert(int& hours, int& minutes, int& delay, string& ampm) 
{ 
    int temp = 0; 

    minutes += delay; 
    if (minutes > 60) { 
     temp = minutes/60; 
     hours += temp; 
     minutes = minutes - temp * 60; 
    } 

    if (hours > 12){ 
     hours -= 12; 
     ampm = "PM"; 
    } 
    else { 
     ampm = "AM"; 
    } 
} 


void output(int& hours, int& minutes, string& ampm) 
{ 
    if (minutes > 0 && minutes < 10) { 
     cout << hours << ":0" << minutes << " " << ampm << endl;; 
    } 
    else if (minutes == 0) { 
     cout << hours << ":0" << minutes << " " << ampm << endl;; 
    } 
    else { 
     cout << hours << ":" << minutes << " " << ampm << endl; 
    } 
}