【发布时间】:2013-05-26 22:58:38
【问题描述】:
我正面临着关于 float 舍入和转换为 int 的非常奇怪的事实。
正如这里所说: http://www.gnu.org/software/libc/manual/html_node/Rounding.html
四舍五入到最接近的可表示值是默认的舍入模式。但好像不是。
所以我创建了这个简单的程序:
#include <fenv.h>
#include <stdio.h>
int a;
double b;
main() {
b=1.3; a=b; printf("%f %d\n",b,a);
b=1.8; a=b; printf("%f %d\n",b,a);
b=-1.3; a=b; printf("%f %d\n",b,a);
b=-1.8; a=b; printf("%f %d\n",b,a);
printf("%d %d %d\n",fegetround(),FE_TONEAREST,FE_TOWARDZERO);
}
程序是用 gcc-4.7 (debian)、cygwin gcc 和 Visual Studio 编译的。输出是一样的,只是FE_TOWARDZERO的定义改变了。
程序输出:
1.300000 1
1.800000 1
-1.300000 -1
-1.800000 -1
0 0 3072
所以我们可以清楚地看到,在所有经过测试的编译器中,舍入模式都设置为FE_TONEAREST(默认),但它们都向零舍入。
为什么?
PS:是的,我可以使用Math.round(),但我想知道为什么会这样。
【问题讨论】:
标签: c math floating-point type-conversion rounding