我需要一个函数来将正整数四舍五入到最接近的整数。潜伏在奥伦德,我发现这很优雅

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

那是什么

谢谢
问候
路卡

最佳答案

这是输出,使用printf代替:
printf("%.15f\t%.15f\t%.15f\n", a, a + 0.5, floor(a + 0.5));
现在,这种不精确性很明显:

10.000000000000000  10.500000000000000  10.000000000000000
10.100000000000000  10.600000000000000  10.000000000000000
10.199999999999999  10.699999999999999  10.000000000000000
10.299999999999999  10.799999999999999  10.000000000000000
10.399999999999999  10.899999999999999  10.000000000000000
10.499999999999998  10.999999999999998  10.000000000000000
10.599999999999998  11.099999999999998  11.000000000000000
10.699999999999998  11.199999999999998  11.000000000000000
10.799999999999997  11.299999999999997  11.000000000000000
10.899999999999997  11.399999999999997  11.000000000000000

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

10-09 06:38