我寫了下面的代碼,它計算兩個給定時間之間的時間差。然而,這項任務也被要求認識穿越午夜。除了確保Delta報告爲正值外,我無法想象在代碼中真正處理這種情況的方法。我也在網上搜索,發現其他一些代碼似乎沒有更好地處理它。請注意;我在問這個算法。我不是在尋找這樣做的功能。這裏是我的代碼:計算兩個不同時間之間的時間差 - 毫秒時間
struct time {
int hour;
int minutes;
int seconds;
};
int main (void)
{
struct time timeDiff (struct time now, struct time later);
struct time result, one, two;
printf("Enter the first time (hh:mm:sec): ");
scanf("%i:%i:%i", &one.hour, &one.minutes, &one.seconds);
printf("Enter the second time (hh:mm:sec): ");
scanf("%i:%i:%i", &two.hour, &two.minutes, &two.seconds);
result = timeDiff(one, two);
printf("Time is: %.2i:%.2i:%.2i\n", result.hour, result.minutes, result.seconds);
return 0;
}
struct time timeDiff (struct time now, struct time later)
{
struct time timeDiff;
timeDiff.hour = later.hour - now.hour;
timeDiff.minutes = later.minutes - now.minutes;
timeDiff.seconds = later.seconds - now.seconds;
return timeDiff;
}
這裏是我發現的代碼在網上:
#include <stdio.h>
struct time
{
int hour;
int minute;
int second;
};
int main(void)
{
struct time time3;
//struct time get_time(struct time d);
//struct time elapsed_time(struct time d, struct time e);
int convert_to_seconds(struct time d);
int elapsed_time(int d, int e);
struct time conver_to_normal_time(int a);
struct time time1 = { 3, 45,15};
struct time time2 = { 9, 44, 03};
int a, b, c;
a = convert_to_seconds(time1);
b = convert_to_seconds(time2);
c = elapsed_time(a, b);
time3 = conver_to_normal_time(c);
printf(" %d:%d:%d", time3.hour, time3.minute, time3.second);
return 0;
}
struct time get_time(struct time d)
{
printf("Give me the time\n");
scanf(" %d:%d:%d", &d.hour, &d.minute, &d.second);
}
int convert_to_seconds(struct time d)
{
struct time time1_seconds;
int totalTime1_seconds;
time1_seconds.hour = d.hour * 3600;
time1_seconds.minute = d.second*60;
time1_seconds.second = d.second;
totalTime1_seconds = time1_seconds.hour + time1_seconds.minute + time1_seconds.second;
return totalTime1_seconds;
totalTime1_seconds = time1_seconds.hour + time1_seconds.minute + time1_seconds.second;
return totalTime1_seconds;
}
int elapsed_time(int d, int e)
{
int result;
result = d - e;
return result;
}
struct time conver_to_normal_time(int a)
{
struct time final_elapse_time;
final_elapse_time.hour = a/3600;
final_elapse_time.minute = (a/60) % 60;
final_elapse_time.second = a % 60;
return final_elapse_time;
}
這聽起來像你有解決你的問題(三角洲的跡象),那麼問題是什麼? –
你已經做出了自己的時間減法,而不考慮任何「借用」。如果那是數百,數十和單位,你會知道如何減去它。對於秒鐘,你可以從分鐘中「借用」60秒等等。在紙上試試。 –
嗨斯科特,是的,我試圖看看如果這是處理這個問題的最好方法,並且我做了任何不正確的假設。 Vane的評論有所幫助。 – maverick