将 char * 转换为 double,而不会丢失 c 中的精度
convert char * to double,without losing precision in c
我需要一些帮助。我必须 将 char * 转换并存储为 double 或 long double 而不会丢失精度。
确实,我尝试使用 strtold 和 atof 方法(还有 strtold),但这些方法正在四舍五入该值。
例如:
char * key ="39.7519707";
double ld =strtod((char*)key,NULL);
printf("%lf", ld);
打印:39.751971
但是 printf("%6.7f",ld)
给了我正确的值,但我无法存储到变量中。
首先,你只需要 %f
格式说明符来打印一个 double
.
然后,您不会因为使用 strtod()
而失去精度,输出 表示 是您如何将 printf()
与 %f
格式说明符。
根据 C11
,章节 §7.21.6.1,fprintf()
[...] If the
precision is missing, it is taken as 6;[...]
接下来,当你这样做时
printf("%6.7f",ld);
精度变为 7,它输出您期望看到的值。
我需要一些帮助。我必须 将 char * 转换并存储为 double 或 long double 而不会丢失精度。
确实,我尝试使用 strtold 和 atof 方法(还有 strtold),但这些方法正在四舍五入该值。
例如:
char * key ="39.7519707";
double ld =strtod((char*)key,NULL);
printf("%lf", ld);
打印:39.751971
但是 printf("%6.7f",ld)
给了我正确的值,但我无法存储到变量中。
首先,你只需要 %f
格式说明符来打印一个 double
.
然后,您不会因为使用 strtod()
而失去精度,输出 表示 是您如何将 printf()
与 %f
格式说明符。
根据 C11
,章节 §7.21.6.1,fprintf()
[...] If the precision is missing, it is taken as 6;[...]
接下来,当你这样做时
printf("%6.7f",ld);
精度变为 7,它输出您期望看到的值。