计算C++军事时间的时差
Calculating Time Difference in military time for C++
我必须编写一个程序,给出以军事时间格式给出的两个时间之间的差异。例如
请输入第一次: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";
}
相关文章:
- C++为构建时间获取QDateTime的可靠方法
- 从持续时间构造std::chrono::system_clock::time_point
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- while循环中while循环的时间复杂度是多少
- 使用简单类型列表实现的指数编译时间.为什么
- 是否可以在编译时初始化数组,以便在运行时不会花费时间?
- 在已经使用Git的情况下减少编译时间
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 从文本文件中读取时钟时间和事件时间并进行处理
- 具有未知值时的时间复杂性
- 如何减少花费的时间
- C++在变量给定的指定时间内关闭电脑
- rcpp函数中的清理时间很长
- C++:floor unix时间戳到UTC月份
- 如何在c++中录制具有精确帧时间戳的视频
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 如何找到纪元时间戳和 std::chrono::system_clock::now 之间的时差(以毫秒为单位)
- 计算C++军事时间的时差
- 军事时间的C++时差