gpt4 book ai didi

c++ - floor() 行为异常

转载 作者:太空狗 更新时间:2023-10-29 20:43:25 28 4
gpt4 key购买 nike

我需要一个函数来将正 double 四舍五入到最接近的整数。潜伏 aorund 我发现这种非常优雅的方式

int x = floor(y + 0.5);

我写了一个简单的测试程序:

double a = 10.0;

for (int i = 0; i < 10; i++) {
cout << a << "\t" << a + 0.5 << "\t" << floor(a + 0.5) << endl;
a += 0.1;
}

但是我收到了一些奇怪的输出

10      10.5    10
10.1 10.6 10
10.2 10.7 10
10.3 10.8 10
10.4 10.9 10
10.5 11 10 <--- should be 11!
10.6 11.1 11
10.7 11.2 11
10.8 11.3 11
10.9 11.4 11

那是什么?

谢谢问候卢卡

最佳答案

通过添加 0.1,您确实添加了一个略低于 0.1 的值。

所以加0.1 5次和加0.5一次是不一样的;您没有完全达到该值。通过再次添加 .5,您不会超过 11,这会产生您观察到的行为。


一个C程序如

#include <stdio.h>
#include <math.h>

int main()
{
double a = 10.0;
int i;
for (i = 0; i < 11; i++) {
printf("%4.19f\t%4.19f\t%4.19f\n", a, a+.5, floor(a + 0.5));
a += 0.1;
}
printf("\n");
for (i = 0; i < 11; i++) {
a = 10.0 + i/10.0;
printf("%4.19f\t%4.19f\t%4.19f\n", a, a+.5, floor(a + 0.5));
}
}

显示在它的输出上

10.0000000000000000000  10.5000000000000000000  10.0000000000000000000
10.0999999999999996447 10.5999999999999996447 10.0000000000000000000
10.1999999999999992895 10.6999999999999992895 10.0000000000000000000
10.2999999999999989342 10.7999999999999989342 10.0000000000000000000
10.3999999999999985789 10.8999999999999985789 10.0000000000000000000
10.4999999999999982236 10.9999999999999982236 10.0000000000000000000
10.5999999999999978684 11.0999999999999978684 11.0000000000000000000
10.6999999999999975131 11.1999999999999975131 11.0000000000000000000
10.7999999999999971578 11.2999999999999971578 11.0000000000000000000
10.8999999999999968026 11.3999999999999968026 11.0000000000000000000
10.9999999999999964473 11.4999999999999964473 11.0000000000000000000

10.0000000000000000000 10.5000000000000000000 10.0000000000000000000
10.0999999999999996447 10.5999999999999996447 10.0000000000000000000
10.1999999999999992895 10.6999999999999992895 10.0000000000000000000
10.3000000000000007105 10.8000000000000007105 10.0000000000000000000
10.4000000000000003553 10.9000000000000003553 10.0000000000000000000
10.5000000000000000000 11.0000000000000000000 11.0000000000000000000
10.5999999999999996447 11.0999999999999996447 11.0000000000000000000
10.6999999999999992895 11.1999999999999992895 11.0000000000000000000
10.8000000000000007105 11.3000000000000007105 11.0000000000000000000
10.9000000000000003553 11.4000000000000003553 11.0000000000000000000
11.0000000000000000000 11.5000000000000000000 11.0000000000000000000

区别:第一次运行是您的方法,累积误差和步长为 0.0999999999999996447,而第二次运行重新计算尽可能接近的 a,使其有可能准确地达到 10.5 和 11.0。

关于c++ - floor() 行为异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15381119/

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