Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在c中将类似浮点的字符串转换为浮点_C_String - Fatal编程技术网

在c中将类似浮点的字符串转换为浮点

在c中将类似浮点的字符串转换为浮点,c,string,C,String,我有这个密码 #include <sys/time.h> #include <stdio.h> #include <stdlib.h> int main() { struct timeval current_time; gettimeofday(&current_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(&current_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);