[問題] C++ 時間換算

看板C_and_CPP (C/C++)作者 (MPower)時間16年前 (2009/03/09 05:12), 編輯推噓2(203)
留言5則, 2人參與, 最新討論串1/1
這是一題24小時換12小時的問題?請高手們幫我看一下為什麼我跑出來會是下列的樣子. Enter the hours for the 24 hour time: 13 Enter the minutes for the 24 hour time: 40 The time converted to 12 hour format is: 80:40 P.M. #include <iostream> using namespace std; // // function declarations // void input(int& hours, int& minutes); void output(int hours, int minutes, char type); int convertTo12Hour(int hours, char& type); int main() { int hours; int minutes; char type; char answer; do { input(hours, minutes); hours = convertTo12Hour(hours, type); output(hours, minutes, type); cout << "Perform another calculation? (y/n): "; cin >> answer; } while ((answer == 'Y') || (answer == 'y')); return 0; } // function main // // function definitions // void input(int& hours, int& minutes) { // // prompt the user for the number of hours in 24 hour format // cout << "Enter the hours for the 24 hour time: "; cin >> hours; // // prompt the user for the number of minutes // cout << "Enter the minutes for the 24 hour time: "; cin >> minutes; } // function input void output(int hours, int minutes, char type) { // // display the output // cout << "The time converted to 12 hour format is: " << hours << ":"; // // special handling for leading 0s on the minutes // cout.width(2); cout.fill('0'); cout << minutes; // // Output A.M. or P.M. based on type. // if (type == 'A') cout << " A.M." << endl; else cout << " P.M." << endl; } // function outpu int convertTo12Hour(int hours, char& type) { if (hours == 0) { hours = 12; return 'A'; } if (hours >= 12) if (hours == 12) return 'P'; else { hours -= 12; return 'P'; } return 'A' } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 71.199.79.106

03/09 06:09, , 1F
你確定你的 convertTo12Hour 做了你想讓它做的事了嗎?
03/09 06:09, 1F

03/09 06:54, , 2F
hours = convertTo12Hour(hours, type);這邊錯了
03/09 06:54, 2F

03/09 06:55, , 3F
你的convertTo12Hour回傳的是A或P,你硬塞到hours裡面
03/09 06:55, 3F

03/09 06:55, , 4F
就變成P讀ASCII碼80了
03/09 06:55, 4F

03/09 06:56, , 5F
    的
03/09 06:56, 5F
文章代碼(AID): #19j3J6G1 (C_and_CPP)
文章代碼(AID): #19j3J6G1 (C_and_CPP)