在此示例中,您將學(xué)習(xí)使用用戶定義的函數(shù)來計(jì)算兩個(gè)時(shí)間段之間的差。
要理解此示例,您應(yīng)該了解以下C語言編程主題:
#include <stdio.h> struct TIME { int seconds; int minutes; int hours; }; void differenceBetweenTimePeriod(struct TIME t1, struct TIME t2, struct TIME *diff); int main() { struct TIME startTime, stopTime, diff; printf("輸入開始時(shí)間。 \n"); printf("輸入小時(shí)、分鐘和秒: "); scanf("%d %d %d", &startTime.hours, &startTime.minutes, &startTime.seconds); printf("輸入停止時(shí)間。 \n"); printf("輸入小時(shí),分鐘和秒: "); scanf("%d %d %d", &stopTime.hours, &stopTime.minutes, &stopTime.seconds); //開始時(shí)間和停止時(shí)間之間的時(shí)差 differenceBetweenTimePeriod(startTime, stopTime, &diff); printf("\n時(shí)差: %d:%d:%d - ", startTime.hours, startTime.minutes, startTime.seconds); printf("%d:%d:%d ", stopTime.hours, stopTime.minutes, stopTime.seconds); printf("= %d:%d:%d\n", diff.hours, diff.minutes, diff.seconds); return 0; } //計(jì)算時(shí)間段之間的差異 void differenceBetweenTimePeriod(struct TIME start, struct TIME stop, struct TIME *diff) { while (stop.seconds > start.seconds) { --start.minutes; start.seconds += 60; } diff->seconds = start.seconds - stop.seconds; while (stop.minutes > start.minutes) { --start.hours; start.minutes += 60; } diff->minutes = start.minutes - stop.minutes; diff->hours = start.hours - stop.hours; }
輸出結(jié)果
輸入開始時(shí)間。 輸入小時(shí)、分鐘和秒: 12 34 55 輸入停止時(shí)間。 輸入小時(shí),分鐘和秒: 8 12 15 時(shí)差: 12:34:55 - 8:12:15 = 4:22:40
在這個(gè)程序中,用戶被要求輸入兩個(gè)時(shí)間段和這兩個(gè)時(shí)期都分別存儲(chǔ)在結(jié)構(gòu)變量startTime和stopTime。
然后,函數(shù)differenceBetweenTimePeriod()計(jì)算時(shí)間段之間的差。從main()函數(shù)顯示結(jié)果而不返回它(使用引用調(diào)用技術(shù))。