简体   繁体   English

浮点运算后四舍五入不一致

[英]Rounding is inconsistent after floating point math

Take the following example (with contrived numbers): 请看以下示例(人为数字):

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

Across multiple runs, the value of d isn't consistent. 在多次运行中, d的值不一致。 Here are two contrived ways the math gets performed: 这是两种人为计算数学的方法:

Execution 1: 执行1:

9.0 / 2.0 == 4.49999... 9.0 / 2.0 == 4.49999 ...

RoundAndCastToInt(4.49999...) == 4 RoundAndCastToInt(4.49999 ...)== 4

Execution 2: 执行2:

9.0 / 2.0 == 4.5 9.0 / 2.0 == 4.5

RoundAndCastToInt(4.5) == 5 RoundAndCastToInt(4.5)== 5

I want to get the same value consistently across different executions and different machines. 我想在不同的执行程序和不同的机器上始终如一地获得相同的值。 In the example above, a result of either 4 or 5 is fine as long as it is always 4 or always 5 . 另外,在上述的例子中,中的任一个结果45 ,只要它是始终是精细4总是 5

This might be stupid with a lot of unsolved details, but I guess it can work when you know the precision of the solution you want... 这可能是愚蠢的,有很多未解决的细节,但是我想当您知道所需解决方案的精度时,它就可以工作...

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM