C 语言范例 - 计算两个时间段的差值

计算两个时间段的差值

/**
 * file: main.c
 * author: 简单教程(www.twle.cn)
 */

#include <stdio.h>

struct TIME
{
  int seconds;
  int minutes;
  int hours;
};

void diff_of_times(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);

    // 计算差值
    diff_of_times(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 diff_of_times(struct TIME start, struct TIME stop, struct TIME *diff)
{
    if(stop.seconds > start.seconds){
        --start.minutes;
        start.seconds += 60;
    }

    diff->seconds = start.seconds - stop.seconds;
    if(stop.minutes > start.minutes){
        --start.hours;
        start.minutes += 60;
    }

    diff->minutes = start.minutes - stop.minutes;
    diff->hours = start.hours - stop.hours;
}

编译运行范例,输出结果如下

$ gcc main.c && ./a.out
输入开始时间:
输入小时、分钟、秒:22 22 22
输入停止时间:
输入小时、分钟、秒: 8 8 8

差值: 22:22:22 - 8:8:8 = 14:14:14

C 语言范例

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.