Jor*_*son 7 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 = "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;
}
Run Code Online (Sandbox Code Playgroud)
我编译并运行这个程序时得到的输出(在带有gcc 4.5.2的Core 2 Duo上)是:
DBL_MIN = 2.225074e-308, x = 2.225074e-310
Error converting '1e-310': Numerical result out of range
y = 1.000000e-310
Run Code Online (Sandbox Code Playgroud)
我的问题是:
谢谢你提供的所有帮助.当我得到反馈时,我会尝试澄清这个问题.
以下是标准对strtod下溢的说法(C99,7.20.1.3p10)
"如果结果下溢(7.12.1),则函数返回一个值,该值的大小不大于返回类型中的最小标准化正数; errno是否获取值ERANGE是实现定义的."
关于ERANGE上strtod溢,这里是glibc的说什么
"当发生下溢时,将引发下溢异常,并返回零(适当签名).errno可能设置为ERANGE,但不保证这一点."
http://www.gnu.org/savannah-checkouts/gnu/libc/manual/html_node/Math-Error-Reporting.html
(请注意,此页面在glibc strtod页面"Parsing of Floats" 上明确链接:http://www.gnu.org/savannah-checkouts/gnu/libc/manual/html_node/Parsing-of-Floats.html