C 两次之间的时间差

C++ Time difference between two times

本文关键字:之间 时间差 两次      更新时间:2023-10-16

该程序的目的是计算开始时间和结束时间之间的时间差。

开始和结束时间将作为4位数字整数输入,并且需要计算时间差。输入的时间表示为HH:mm,没有":"。

Example: 
first time: 0800
second time: 1755
Time elapsed: 9 hr and 55 min

这是我拥有的代码:

int main()
{
int first_time;
int second_time;
int dif_time;
double mod_time;
cout<<"Enter first time" << endl;
cin>>first_time;
cout<<"Enter second time" << endl;
cin>>second_time;
dif_time = second_time - first_time;
mod_time = dif_time % 60;
std::cout << "Time elapsed: " << dif_time << " hours" << mod_time << " minutes" << endl;
}

问题是它确实正确地输出了时间。关于如何改进该计划的任何建议将不胜感激。

最好在几分钟内转换所有内容,计算差异,然后转换为小时和分钟:

#include <iostream>
int main() 
{
    int first_time;
    int second_time;
    std::cout << "Enter first time" << std::endl;
    std::cin >> first_time;
    std::cout << "Enter second time" << std::endl;
    std::cin >> second_time;
    int first_time_min = first_time / 100 * 60 + first_time % 100;
    int second_time_min = second_time / 100 * 60 + second_time % 100;
    int diff_time_min = second_time_min - first_time_min;
    std::cout << "Time elapsed: " << diff_time_min / 60 << " hours " << diff_time_min % 60 << " minutes" << std::endl;
}

可能的解决方案:

#include <iostream>
int main() {
    int first_time;
    int second_time;
    int dif_time_in_minutes;
    int hours, minutes;
    std::cout << "Enter first time:";
    std::cin >> first_time;
    std::cout << "Enter second time:";
    std::cin >> second_time;
    dif_time_in_minutes = (second_time / 100)*60 + (second_time % 100) - 
        (first_time / 100) * 60 + (first_time % 100);
    hours = dif_time_in_minutes / 60;
    minutes = dif_time_in_minutes % 60;
    std::cout << "Time elapsed: " << hours << " hours " << minutes << " minutes" << std::endl;
}