嘿,谢谢您的光临。如果有人以前遇到过这个问题,我只是想说我很抱歉。
我花了几个小时在论坛和谷歌上搜索类似的问题,但到目前为止还没有运气。
我这个程序的目的是打印出 24 小时格式的两个时间之间经过的时间。
到目前为止,我想我只能将经过的第一个和第二个“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;
}
不要区分小时、分钟和秒之间的差异。将两个时间转换为自午夜以来的秒数,并计算它们之间的差值。然后转换回 hh:mm:ss。
顺便说一句:time.h中的结构和函数可以提供帮助。
假设时间在同一天(同一日期),解决问题的最佳方法是将时间从午夜格式转换为秒,例如:
long seconds1 = (hours1 * 60 * 60) + (minutes1 * 60) + seconds1;
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;
#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;
}