gpt4 book ai didi

c - math.h 默认舍入模式不明确

转载 作者:太空宇宙 更新时间:2023-11-04 08:56:14 25 4
gpt4 key购买 nike

我面临着关于 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() 但我想知道为什么会这样。

最佳答案

因为舍入模式适用于浮点舍入函数。转换为 int 总是会被截断。

关于c - math.h 默认舍入模式不明确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16851904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com