C 程序,用于计算两个时间段之间的差
输入开始和结束时间,包括小时、分钟和秒。最后,我们需要找出开始和结束时间之间的差。
找出开始和结束时间之间的差的逻辑如下 −
while (stop.sec > start.sec){
--start.min;
start.sec += 60;
}
diff->sec = start.sec - stop.sec;
while (stop.min > start.min) {
--start.hrs;
start.min += 60;
}
diff->min = start.min - stop.min;
diff->hrs = start.hrs - stop.hrs;示例
以下程序用于找出开始和结束时间之间的差 −
#include <stdio.h>
struct time {
int sec;
int min;
int hrs;
};
void diff_between_time(struct time t1,
struct time t2,
struct time *diff);
int main(){
struct time start_time, stop_time, diff;
printf("Enter start time.
");
printf("Enter hours, minutes and seconds: ");
scanf("%d %d %d", &start_time.hrs,
&start_time.min,
&start_time.sec);
printf("Enter the stop time.
");
printf("Enter hours, minutes and seconds: ");
scanf("%d %d %d", &stop_time.hrs,
&stop_time.min,
&stop_time.sec);
// Difference between start and stop time
diff_between_time(start_time, stop_time, &diff);
printf("
time Diff: %d:%d:%d - ", start_time.hrs,
start_time.min,
start_time.sec);
printf("%d:%d:%d ", stop_time.hrs,
stop_time.min,
stop_time.sec);
printf("= %d:%d:%d
", diff.hrs,
diff.min,
diff.sec);
return 0;
}
// Computes difference between time periods
void diff_between_time(struct time start,
struct time stop,
struct time *diff){
while (stop.sec > start.sec) {
--start.min;
start.sec += 60;
}
diff->sec = start.sec - stop.sec;
while (stop.min > start.min) {
--start.hrs;
start.min += 60;
}
diff->min = start.min - stop.min;
diff->hrs = start.hrs - stop.hrs;
}输出
执行以上程序时,将产生以下结果 −
Enter start time. Enter hours, minutes and seconds: 12 45 57 Enter the stop time. Enter hours, minutes and seconds: 20 35 20 time Diff: 12:45:57 - 20:35:20 = -8:10:37
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP