在c中将类似浮点的字符串转换为浮点
我有这个密码在c中将类似浮点的字符串转换为浮点,c,string,C,String,我有这个密码 #include <sys/time.h> #include <stdio.h> #include <stdlib.h> int main() { struct timeval current_time; gettimeofday(¤t_time, NULL); printf("seconds : %ld\nmicro seconds : %ld\n", current_time.tv_s
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
struct timeval current_time;
gettimeofday(¤t_time, NULL);
printf("seconds : %ld\nmicro seconds : %ld\n",
current_time.tv_sec, current_time.tv_usec);
char timestamp[100];
sprintf(timestamp,"%ld.%ld",current_time.tv_sec,current_time.tv_usec);
printf("timestamp in char: %s\n", timestamp);
float timestamp_f;
timestamp_f = strtold(timestamp,NULL);
printf("timestamp in float: %10.6f\n",timestamp_f);
return 0;
}
小数+最后一位是8
,而不是0
我使用了strof
,但仍然得到了一些类似的结果:
seconds : 1615776930
micro seconds : 767048
timestamp in char: 1615776930.767048
timestamp in float: 1615776896.000000
谢谢
小数+最后一位是8,而不是0
float
缺少精度。使用double
或long double
使您的类型一致,例如double
和strtod
(而不是strtold
)。请注意,float
只有约7位小数精度,而double
只有约16位小数精度
double timestamp_f;
timestamp_f = strtod(timestamp,NULL);
您正在以高精度转换值,然后通过将结果转换为单个精度
float
,放弃该精度。不要使用float
。使用double
。因此我将timestamp\u f
更改为double
,格式将是%lf
,而不是%10.6f
。另外%ld.%ld
-->%ld.%06ld
%10.6f
保持正常l
在打印时没有功能上的区别。不要使用strtof,因为浮点只有7位有效数字。您需要使用strtold
,但该函数返回一个长双精度
,因此您需要将其分配给该类型的变量。更改浮动时间戳\u f代码>到长双时间戳
并确保printf说明符为%10.6Lf
,以便printf知道它是一个长双精度。
double timestamp_f;
timestamp_f = strtod(timestamp,NULL);