计算C++军事时间的时差

Calculating Time Difference in military time for C++

本文关键字:时差 时间 C++ 计算      更新时间:2023-10-16

我必须编写一个程序,给出以军事时间格式给出的两个时间之间的差异。例如

请输入第一次: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";
}