分配给变量

问题描述

我有一个简单的时间戳记问题。我正在尝试使用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进行编程,我知道这个问题可能很简单。

解决方法

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