C中的舍入(math.h)不能正常工作

时间:2017-10-27 13:08:11

标签: c math.h

#include <stdio.h>
#include <math.h>

int main(){
  printf("Rounded value of 6*0.95*0.25 = %.2f\n", round(6*0.95*0.25*100)/100);
  printf("Rounded value of 1.425 = %.2f\n", round(1.425*100)/100);
}

我怀疑这是与双打和各自算术的准确性有关,但我怎么能解决这个问题(这样6 * 0.95 * 0.25这是1.425将四舍五入到1.43)我不知道.. ..

(我使用的是GNU编译器最新版本(1.7件))

帮助赞赏

我想要回到2 d.p。

以下是输出:

圆形值6 * 0.95 * 0.25 = 1.42
圆形值1.425 = 1.43

https://onlinegdb.com/r1ZtZ2lCW

我想要

圆形值6 * 0.95 * 0.25 = 1.43
圆形值1.425 = 1.43

4 个答案:

答案 0 :(得分:2)

math.h中的舍入工作完全正常。当您为程序提供像1.425这样的十进制数时,它会将其存储为数字的最接近的二进制表示形式。数字1.425 = 57 / 40.因为40不是2的幂,所以没有这个数字的精确二进制表示。在这种情况下,存储的数字略小于1.425,因此数字向下舍入。

停止此舍入差异的唯一通用解决方案是使用十进制浮点实现。除非硬件支持,否则这将比二进制浮点实现慢得多。

答案 1 :(得分:0)

我的解决方案是做出以下功能:

double twoDPRoundHack(double x){
  return round(round(x*10000)/100)/100;
}

这似乎有效

#include <stdio.h>
#include <math.h>

double twoDPRoundHack(double x){
  return round(round(x*1000)/100)/100;
}

int main(){
  printf("Rounded value of 6*0.95*0.25 = %.2f\n", 
         twoDPRoundHack(6*0.95*0.25*100));
   printf("Rounded value of 1.425 = %.2f\n", round(1.425*100)/100);
}
显然,它被存储为142.499999999999 ...

答案 2 :(得分:0)

如果您正在执行print语句的计算方面,您将得到正确的答案

#include <stdio.h>
#include <math.h>

int main (){
    float value = 6*0.95*0.25;
    printf ("Rounded value of 6*0.95*0.25 = %.2f\n",
    round(value*100)/100);

    printf ("Rounded value of 1.425 = %.2f\n", round (1.425 * 100) / 100);

}

输出

Rounded value of 6*0.95*0.25 = 1.43
Rounded value of 1.425 = 1.43 

答案 3 :(得分:0)

这肯定似乎没有按预期工作。我不知道它是否有多大帮助,但改变乘法的顺序似乎可以解决问题。

#include <stdio.h>
#include <math.h>

int main(){
  printf("Rounded value of 6*0.95*0.25 (hundred last) = %.2f\n", round(6*0.95*0.25*100)/100);
  printf("Rounded value of 6*0.95*0.25 (hundred first) = %.2f\n", round(100*6*0.95*0.25)/100);
  printf("Rounded value of 1.425 = %.2f\n", round(100*1.425)/100);
}

输出

Rounded value of 6*0.95*0.25 (hundred last) = 1.42
Rounded value of 6*0.95*0.25 (hundred first) = 1.43
Rounded value of 1.425 = 1.43

这显然是超级哑巴!也许这就是问题的原因。