c - 使用当前时间获取时差

标签 c

我为我的 child (8 岁)制作了一个数学游戏,有时我决定向他展示他需要多少时间来回答这个问题,所以我决定在这里使用函数时间。

我写了下面的程序:

#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

struct setClock{
    int hour;
    int minutes;
    int seconds;
};

struct setClock currTime(void);
void timeCheck(struct setClock myClock[2]);

int main(void){
    struct setClock myClock[2];

    myClock[0] = currTime();
    printf("Start Time: %d:%d:%d\n\n", myClock[0].hour, myClock[0].minutes, myClock[0].seconds );

    sleep(5);

    myClock[1] = currTime();
    printf("End Time:   %d:%d:%d\n", myClock[1].hour, myClock[1].minutes, myClock[1].seconds );

    timeCheck(myClock);

    return 0;

}

struct setClock currTime(void){
    struct setClock ret;
    struct tm *tm;
    time_t myTime;

    myTime=time(NULL);
    tm=localtime(&myTime);

    ret.hour = tm->tm_hour;
    ret.minutes = tm->tm_min;
    ret.seconds = tm->tm_sec;

    return ret;
}

void timeCheck(struct setClock myClock[2]){
    int hour;
    int minute;

    time_t end, start;
    double diff;

    start = (time_t)((myClock[0].hour * 60 + myClock[1].hour) * 60) ;
    end   = (time_t)((myClock[0].minutes * 60 + myClock[1].minutes) * 60) ;

    if( end < start ){
        end += 24 * 60 * 60 ;
    }

    diff = difftime(end, start);

    hour = (int) diff / 3600;
    minute = (int) diff % 3600 / 60;
    printf("\n\n");
    printf("The elapsed time is  %d Hours - %d Minutes\n", hour, minute);
}

当我运行它时,我得到不同的输出,例如:

Start Time: 16:19:2

End Time:   16:19:7


The elapsed time is  3 Hours - 3 Minutes

或者:

Start Time: 16:19:14

End Time:   16:19:19


The elapsed time is  1 Hours - 1 Minutes

但输出应该是:

The elapsed time is  0 Hours - 0 Minutes

我真的不知道我的timeCheck 函数出了什么问题。 无论如何,如果我修复它,我需要如何扩展它来打印:

The elapsed time is  0 Hours - 0 Minutes - 5 Seconds.

最佳答案

start = (time_t)((myClock[0].hour * 60 + myClock[1].hour) * 60) ;
end   = (time_t)((myClock[0].minutes * 60 + myClock[1].minutes) * 60) ;

这段代码似乎是胡说八道。我觉得应该是这样

start = (time_t)((myClock[0].hour * 60 + myClock[0].minutes) * 60 + myClock[0].seconds) ;
end   = (time_t)((myClock[1].hour * 60 + myClock[1].minutes) * 60 + myClock[1].seconds) ;

然后,让函数打印您想要的内容。

  1. int minute; 之后添加一个变量 int second;
  2. minute = (int) diff % 3600/60; 之后添加计算 second = (int) diff % 60;
  3. 让它打印结果
    printf("耗时是 %d 小时 - %d 分钟 - %d 秒。\n", 小时, 分钟, 秒);

关于c - 使用当前时间获取时差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34454868/

相关文章:

c++ - Dev-C++ 4.9.9.2 项目选项不起作用

c - 如何准确测量执行时间(当 < 1 毫秒时)

c++ - 这个 stdout 重定向是如何工作的?

c - 逻辑哪里错了?

C: 动态链接 OpenSSL 库时出错

c - free() 如何知道要释放多少内存?

c - 重新分配一个字符串数组

C 中取消线程

c - fork() 命令

c - Linux 中的 fflush 函数与什么相同?