编辑这个页面须要登录或更高权限!
在此示例中,您将学习使用用户定义的函数来计算两个时间段之间的差。
要理解此示例,您应该了解以下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("输入开始时间。 \n"); printf("输入小时、分钟和秒: "); scanf("%d %d %d", &startTime.hours, &startTime.minutes, &startTime.seconds); printf("输入停止时间。 \n"); printf("输入小时,分钟和秒: "); scanf("%d %d %d", &stopTime.hours, &stopTime.minutes, &stopTime.seconds); //开始时间和停止时间之间的时差 differenceBetweenTimePeriod(startTime, stopTime, &diff); printf("\n时差: %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; } //计算时间段之间的差异 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; }
输出结果
输入开始时间。 输入小时、分钟和秒: 12 34 55 输入停止时间。 输入小时,分钟和秒: 8 12 15 时差: 12:34:55 - 8:12:15 = 4:22:40
在这个程序中,用户被要求输入两个时间段和这两个时期都分别存储在结构变量startTime和stopTime。
然后,函数differenceBetweenTimePeriod()计算时间段之间的差。从main()函数显示结果而不返回它(使用引用调用技术)。