将C字符串转换为双精度或从双精度转换时的奇怪行为
我很难理解C的规则,当打印双精度或将字符串转换为双精度时,应该假设什么样的精度。以下程序应说明我的观点:将C字符串转换为双精度或从双精度转换时的奇怪行为,c,printf,ieee-754,strtod,C,Printf,Ieee 754,Strtod,我很难理解C的规则,当打印双精度或将字符串转换为双精度时,应该假设什么样的精度。以下程序应说明我的观点: #include <errno.h> #include <float.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char **argv) { double x, y; const char *s
#include <errno.h>
#include <float.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
double x, y;
const char *s = "1e-310";
/* Should print zero */
x = DBL_MIN/100.;
printf("DBL_MIN = %e, x = %e\n", DBL_MIN, x);
/* Trying to read in floating point number smaller than DBL_MIN gives an error */
y = strtod(s, NULL);
if(errno != 0)
printf(" Error converting '%s': %s\n", s, strerror(errno));
printf("y = %e\n", y);
return 0;
}
我的问题是:
DBL_MIN
是最小的标准化值以下是标准对strtod下溢(C99,7.20.1.3p10)的说明 如果结果下溢(7.12.1),函数返回一个值,其大小不大于返回类型中最小的标准化正数;errno是否获取值ERANGE由实现定义 关于
strtod
underflow上的ERANGE
,glibc是这么说的
发生下溢时,会引发下溢异常,并返回零(正确签名)。errno可以设置为ERANGE,但这不能保证
(请注意,此页面在glibcstrtod
页面“浮动解析”上显式链接:
首先:
DBL_MIN=2.225074e-308
没有多大意义,因为最小IEEE DP值是4.94066e-324
。这解释了为什么除以100
仍然正确。但问题是为什么DBL_MIN
不是4.94066e-324
。下面澄清:DBL_MIN是最小的标准化值。谢谢,这是非常有用的信息。我有点希望strod在这种情况下不会标记错误,但我可以看到其原理。我会解决它。
DBL_MIN = 2.225074e-308, x = 2.225074e-310
Error converting '1e-310': Numerical result out of range
y = 1.000000e-310