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

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



示例:程序与时间差异

  1. // Computes time difference of two time period
  2. // Time periods are entered by the user
  3. #include <iostream>
  4. using namespace std;
  5. struct TIME
  6. {
  7. int seconds;
  8. int minutes;
  9. int hours;
  10. };
  11. void computeTimeDifference(struct TIME, struct TIME, struct TIME *);
  12. int main()
  13. {
  14. struct TIME t1, t2, difference;
  15. cout << "Enter start time." << endl;
  16. cout << "Enter hours, minutes and seconds respectively: ";
  17. cin >> t1.hours >> t1.minutes >> t1.seconds;
  18. cout << "Enter stop time." << endl;
  19. cout << "Enter hours, minutes and seconds respectively: ";
  20. cin >> t2.hours >> t2.minutes >> t2.seconds;
  21. computeTimeDifference(t1, t2, &difference);
  22. cout << endl << "TIME DIFFERENCE: " << t1.hours << ":" << t1.minutes << ":" << t1.seconds;
  23. cout << " - " << t2.hours << ":" << t2.minutes << ":" << t2.seconds;
  24. cout << " = " << difference.hours << ":" << difference.minutes << ":" << difference.seconds;
  25. return 0;
  26. }
  27. void computeTimeDifference(struct TIME t1, struct TIME t2, struct TIME *difference){
  28. if(t2.seconds > t1.seconds)
  29. {
  30. --t1.minutes;
  31. t1.seconds += 60;
  32. }
  33. difference->seconds = t1.seconds - t2.seconds;
  34. if(t2.minutes > t1.minutes)
  35. {
  36. --t1.hours;
  37. t1.minutes += 60;
  38. }
  39. difference->minutes = t1.minutes-t2.minutes;
  40. difference->hours = t1.hours-t2.hours;
  41. }

输出

  1. Enter hours, minutes and seconds respectively: 11
  2. 33
  3. 52
  4. Enter stop time.
  5. Enter hours, minutes and seconds respectively: 8
  6. 12
  7. 15
  8. TIME DIFFERENCE: 11:33:52 - 8:12:15 = 3:21:37

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

然后,computeTimeDifference()函数计算时间段之间的时差,结果从main()函数显示在屏幕上,而不会返回(通过引用调用)。