c++ 两次之间的经过时间,24小时格式hh:mm:ss

41zrol4v  于 11个月前  发布在  其他
关注(0)|答案(3)|浏览(107)

嘿,谢谢你的来访。我只是想说,如果有人以前遇到过这个问题,我真的很抱歉。
我已经花了几个小时在论坛和谷歌上搜索类似的问题,但到目前为止还没有运气。
这个程序的目的是打印出两个时间之间经过的时间,格式为24小时。
到目前为止,我想我只得到了我的头周围转换过去的第1和第2“hh”到正确的24时间,但有麻烦理解如何做分钟和秒。
我真的很感激任何指导,这将是非常有帮助的。干杯。

int main()
    {
        char time1[ 48 ] = "14:48:34";
        char time2[ 48 ] = "02:18:19";

        int hour1;
        int min1;
        int sec1;

        int hour2;
        int min2;
        int sec2;

        int seconds;
        int temp;

        //time1
        hour1 = atoi( strtok( time1, ":" ) );
        min1 = atoi( strtok( NULL, ":" ) );
        sec1 = atoi( strtok( NULL, ":" ) );

        //time2
        hour2 = atoi( strtok( time2, ":" ) );
        min2 = atoi( strtok( NULL, ":" ) );
        sec2 = atoi( strtok( NULL, ":" ) );

        seconds = hour1 * 60 * 60; //convert hour to seconds
        ...

        system("PAUSE");
        return 0;
    }

字符串

yqlxgs2m

yqlxgs2m1#

不要取小时、分钟和秒之间的差。将两个时间都转换为自午夜以来的秒,并取它们之间的差。然后转换回hh:mm:ss。
顺便说一下:time.h中的结构和函数可以提供帮助。

mbyulnm0

mbyulnm02#

假设时间是在同一天(同一日期),解决问题的最佳方法是将时间从午夜格式转换为秒,如:
第一个月
long seconds2 = (hours2 * 60 * 60) + (minutes2 * 60) + seconds2;
long deference = fabs(seconds1 - seconds2);
然后将其转换回h:m:s格式,如:
int hours = deference / 60 / 60;
int minutes = (deference / 60) % 60;
int seconds = deference % 60;

ua4mk5z4

ua4mk5z43#

#include <stdio.h>

int main() {
    int h1, m1, s1, h2, m2, s2;
    
    // Input the first time
    scanf("%d:%d:%d", &h1, &m1, &s1);
    
    // Input the second time
    scanf("%d:%d:%d", &h2, &m2, &s2);
    
    // Calculate the total elapsed time in seconds
    int totalSeconds1 = h1 * 3600 + m1 * 60 + s1;
    int totalSeconds2 = h2 * 3600 + m2 * 60 + s2;
    
    int elapsedTime = totalSeconds2 - totalSeconds1;
    
    // Output the difference in seconds
    printf("%d\n", elapsedTime);

    return 0;
}

字符串

相关问题