gpt4 book ai didi

c - 如何在 C 中进行舍入?

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

我有一个代码示例:

float f = 3.55f;
printf("%.1f\n", f);

结果是 3.5,而不是 3.6,这是我们想要的。

float delta = 1e-7;
float f = 3.55f;
printf("%.1f\n", f+delta);

现在结果是3.6,但是当f是0.0499999f时;

printf("%.1f\n", f+delta);

结果是 0.1,而不是 0.0。

我需要一个将 3.55 转换为 3.6,将 0.0499999 转换为 0.0 的函数,有人提供线索吗?

最佳答案

与许多浮点问题一样,问题在于您的值 isn't really 3.55 :

float f = 3.55f;
printf("%.10f\n", f); // 3.5499999523

另见 http://floating-point-gui.de/ .

因此,除非您使用 ceil(),否则此值永远不会向上舍入。

关于c - 如何在 C 中进行舍入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17000582/

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