我必须编写一个程序,以军事时间格式给出两次之间的差值。例如,
请输入第一次:1730
请输入第二次:0900
输出= 15小时30分钟
这是我想出的程序(*不允许在if语句,循环或函数中使用)
我只需要知道这是对还是错?
int main()
{
int first;
int second;
cout << "Please enter the first time:";
cin >> first;
cout << endl;
cout << "Please enter the second time:";
cin >> second;
cout << endl;
int am = first - 1200;
second = second + 1200;
int amhour = am/100;
int ammins = am%100;
int hours = second - amhour*100;
int real_hr = hours - 40;
int final_time = real_hr - ammins;
int final_hours = final_time/100;
int final_mins = final_time%100;
cout << final_hours << " hours and " << final_mins << " minutes." << endl;
return 0;
}
最佳答案
我首先将每次转换为“自午夜以来的分钟数”,然后从第二个中减去第一个,然后使用它来形成输出。
但是,您可能需要考虑到,例如,如果第一次是2330
而第二次是0030
(跨越日期边界),则减法会给您带来负数。
您可以通过简单地将1440分钟(一天)添加到该差异中,然后使用取模运算符来减少这一天(如果超过一天)来解决此问题。
因此,我将从以下内容开始:
#include <iostream>
int main() {
// Get times from user.
int first, second;
std::cout << "Please enter the first time: "; std::cin >> first;
std::cout << "Please enter the second time: "; std::cin >> second;
// Convert both to minutes since midnight.
first = (first / 100) * 60 + first % 100;
second = (second / 100) * 60 + second % 100;
// Work out time difference in minutes, taking into
// account possibility that second time may be earlier.
// In that case, it's treated as the following day.
const int MINS_PER_DAY = 1440;
int minutes = (second + MINS_PER_DAY - first) % MINS_PER_DAY;
// Turn minutes into hours and residual minutes, then output.
int hours = minutes / 60;
minutes = minutes % 60;
std::cout << hours << " hours and " << minutes << " minutes.\n";
}