通过添加 0.1,您确实添加了一个略低于 0.1 的值。
所以5次加0.1和加0.5一次是不一样的;你没有完全达到那个值。通过再次添加 0.5,您不会超过 11,这会产生您观察到的行为。
交流节目如
#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。