计算两个时间段的差值
运行效果:
代码实现:
#include<stdio.h>typedef struct {int h; // 时int m; // 分int s; // 秒
}Time;void fun(Time T[2], Time& diff)
{int sum_s[2] = { 0 }; for (int i = 0; i <= 1; i++) { // 统一为秒数sum_s[i] = T[i].h * 60 * 60 + T[i].m * 60 + T[i].s;}// 时差int diff_s = sum_s[0] >= sum_s[1] ? (sum_s[0] - sum_s[1]) : (sum_s[1] - sum_s[0]);diff.h = diff_s / (60 * 60);// 分差diff_s = diff_s % (60 * 60);diff.m = diff_s / 60;// 秒差diff_s = diff_s % 60;diff.s = diff_s;
}int main()
{Time T[2];Time diff = {0};// 输入for (int i = 0; i <= 1; i++) {printf("请输入第%d个时间的小时:",i+1);scanf_s("%d", &T[i].h);printf("请输入第%d个时间的分钟:",i+1);scanf_s("%d", &T[i].m);printf("请输入第%d个时间的秒数:",i+1);scanf_s("%d", &T[i].s);}// 计算时间差fun(T, diff);// 输出for (int i = 0; i <= 1; i++) {printf("第%d个时间:%02d时%02d分%02d秒\n", i+1,T[i].h,T[i].m,T[i].s);}printf("相差时间:%02d时%02d分%02d秒\n", diff.h, diff.m, diff.s);return 0;
}