我无法理解 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;
}
当我编译和运行这个程序(在带有 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
我的问题是:
- 为什么 x 打印为非零数字?我知道编译器有时会出于计算目的将双精度类型提升为更高精度的类型,但 printf 不应该将 x 视为 64 位双精度类型吗?
- 如果 C 库偷偷使用扩展精度浮点数,为什么 strtod 在尝试转换这些小数时设置 errno?为什么它会产生正确的结果呢?
- 这种行为只是一个错误,是我的特定硬件和开发环境的结果吗?(不幸的是,我目前无法在其他平台上进行测试。)
谢谢你提供的所有帮助。当我得到反馈时,我会尝试澄清这个问题。