簡體   English   中英

浮點運算后四舍五入不一致

[英]Rounding is inconsistent after floating point math

請看以下示例(人為數字):

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

我想在不同的執行程序和不同的機器上始終如一地獲得相同的值。 另外,在上述的例子中,中的任一個結果45 ,只要它是始終是精細4總是 5

這可能是愚蠢的,有很多未解決的細節,但是我想當您知道所需解決方案的精度時,它就可以工作...

#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