简体   繁体   English

C ++两次之间的时差

[英]C++ Time difference between two times

The objective of this program is to calculate the time difference between a start time and an end time. 该程序的目的是计算开始时间和结束时间之间的时间差。

The start and end time will be entered as an 4-digital integer, and the time difference will need to be computed. 开始时间和结束时间将以4位数字整数形式输入,并且需要计算时间差。 The inputted times are represented as hh:mm, without the ":". 输入的时间表示为hh:mm,不带“:”。

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

This is the code I have: 这是我的代码:

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;

}

The problem is that it does output the time in hours correctly. 问题在于它确实以小时为单位正确输出时间。 Any suggestions on how to improve this program would be greatly appreciated. 任何有关如何改进此程序的建议将不胜感激。

Would probably be better to convert everything in minutes, calculate the difference and then convert to hours and minutes: 将所有内容都转换为分钟,计算出差然后转换为小时和分钟可能会更好:

#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;
}

Possible solution: 可能的解决方案:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM