浮点数学运算后舍入不一致

Rounding is inconsistent after floating point math

本文关键字:舍入 不一致 运算 浮点数      更新时间:2023-10-16

以以下示例为例(带有人为的数字(:

double a = 9.0, b = 2.0;
double c = a / b;
int d = RoundAndCastToInt(c);

在多次运行中,d的值不一致。以下是两种人为的数学执行方式:

执行 1:

9.0/2.0 == 4.49999...

RoundAndCastToInt(4.49999...( == 4

执行 2:

9.0/2.0 == 4.5

RoundAndCastToInt(4.5( == 5

我希望在不同的执行和不同的机器上一致地获得相同的值。在上面的示例中,只要始终4始终545的结果就可以了。

对于

很多未解决的细节,这可能是愚蠢的,但我想当你知道你想要的解决方案的精度时,它可以工作......

#include <stdio.h>
#include <math.h>
int main(int argc, char * argv[]) {
  float i = 5.3 / 4.7;
  float j = 5.3 / 4.7;
  printf("i %f n", round(i * 10000.0) / 10000.0);
  printf("j %f n", round(j * 10000.0) / 10000.0);

  return 0;
}