原文: https://www.programiz.com/c-programming/examples/time-structure

在此示例中,您将学习使用用户定义的函数计算两个时间段之间的差。

要理解此示例,您应该了解以下 C 编程主题:


计算两个时间段之间的差异

  1. #include <stdio.h>
  2. struct TIME {
  3. int seconds;
  4. int minutes;
  5. int hours;
  6. };
  7. void differenceBetweenTimePeriod(struct TIME t1,
  8. struct TIME t2,
  9. struct TIME *diff);
  10. int main() {
  11. struct TIME startTime, stopTime, diff;
  12. printf("Enter the start time. \n");
  13. printf("Enter hours, minutes and seconds: ");
  14. scanf("%d %d %d", &startTime.hours,
  15. &startTime.minutes,
  16. &startTime.seconds);
  17. printf("Enter the stop time. \n");
  18. printf("Enter hours, minutes and seconds: ");
  19. scanf("%d %d %d", &stopTime.hours,
  20. &stopTime.minutes,
  21. &stopTime.seconds);
  22. // Difference between start and stop time
  23. differenceBetweenTimePeriod(startTime, stopTime, &diff);
  24. printf("\nTime Difference: %d:%d:%d - ", startTime.hours,
  25. startTime.minutes,
  26. startTime.seconds);
  27. printf("%d:%d:%d ", stopTime.hours,
  28. stopTime.minutes,
  29. stopTime.seconds);
  30. printf("= %d:%d:%d\n", diff.hours,
  31. diff.minutes,
  32. diff.seconds);
  33. return 0;
  34. }
  35. // Computes difference between time periods
  36. void differenceBetweenTimePeriod(struct TIME start,
  37. struct TIME stop,
  38. struct TIME *diff) {
  39. while (stop.seconds > start.seconds) {
  40. --start.minutes;
  41. start.seconds += 60;
  42. }
  43. diff->seconds = start.seconds - stop.seconds;
  44. while (stop.minutes > start.minutes) {
  45. --start.hours;
  46. start.minutes += 60;
  47. }
  48. diff->minutes = start.minutes - stop.minutes;
  49. diff->hours = start.hours - stop.hours;
  50. }

输出

  1. Enter the start time.
  2. Enter hours, minutes and seconds: 12
  3. 34
  4. 55
  5. Enter the stop time.
  6. Enter hours, minutes and seconds: 8
  7. 12
  8. 15
  9. Time Difference: 12:34:55 - 8:12:15 = 4:22:40

在该程序中,要求用户输入两个时间段,这两个时间段分别存储在结构变量startTimestopTime中。

然后,函数differenceBetweenTimePeriod()计算时间段之间的差。 结果从main()函数显示而不返回(使用按引用调用技术)。