1

我有一个简单的时间戳问题。我正在尝试使用时间戳gettimeofday,当我将值打印到终端时,它一切正常,但是当我将它分配给一个变量时,它没有。我不知道我做错了什么。代码和输出如下所示:

#include <stdio.h>
#include <sys/time.h>
#include <windows.h>

int main(int argc, char const *argv[])
{
    struct timeval t_struct;
    while(1){
        gettimeofday(&t_struct, NULL);
        printf("Print only: %f \n", (float) t_struct.tv_sec + (float) t_struct.tv_usec/1000000);
        float timestamp = (float) t_struct.tv_sec + (float) t_struct.tv_usec/1000000;
        printf("Assigned  : %f \n", timestamp);
        Sleep(100);
    }
    return 0;
}

输出:

Print only: 1598259371.284617 
Assigned  : 1598259328.000000 
Print only: 1598259371.385117 
Assigned  : 1598259328.000000 
Print only: 1598259371.485873 
Assigned  : 1598259328.000000 

请注意,我习惯于使用 Python 而不是 C 编程,我知道这个问题可能是微不足道的。

4

1 回答 1

1

解决方案是将变量类型更改为double而不是,float我还将除法更改/1000000.0为避免整数除法。

于 2020-08-24T09:28:19.347 回答