简体   繁体   English

为什么printf(“%。2f”,(double)12.555)返回12.55?

[英]Why does printf(“%.2f”, (double) 12.555) return 12.55?

I was writing a program where I had to round double to second decimal place. 我正在编写一个程序,我不得不将其加倍到小数点后第二位。 I noticed printf("%.2f", (double) 12.555) return 12.55 . 我注意到printf(“%。2f”,(double)12.555)返回12.55 However, printf("%.2f", (float) 12.555) returns 12.56 . 但是, printf(“%。2f”,(float)12.555)返回12.56 Can anyone explain why this happens? 谁能解释为什么会这样?

12.555 is a number that is not representable precisely in binary floating point. 12.555是一个在二进制浮点中无法精确表示的数字。 It so happens that the closest value to 1.2555 that is representable in double precision floating point on your system is slightly less than 1.2555, and the closest value to 1.2555 that is representable in single precision floating point is slightly more than 1.2555. 碰巧的是,在系统上以双精度浮点表示的最接近1.2555的值略小于1.2555,并且在单精度浮点中可表示的最接近1.2555的值略大于1.2555。

Assuming the rounding mode used by the conversion is round to nearest (ties to even), which is the default in IEEE 754 standard, then the described output is to be expected. 假设转换使用的舍入模式是舍入到最接近的(与偶数相关),这是IEEE 754标准中的默认值,则可以预期所描述的输出。

Floats and doubles are stored internally using IEEE 754 representation. 使用IEEE 754表示在内部存储浮点数和双精度数。 The part that is relevant to your question is that both floats and doubles store the closest to the decimal number they can, given the limits of their representation. 与您的问题相关的部分是浮点数和双精度数都存储最接近它们可以的十进制数,给定其表示的限制。 Roughly speaking, those limits are to do with the conversion of the decimal part of the original number to a binary number with a finite number of bits. 粗略地说,这些限制与将原始数字的小数部分转换为具有有限位数的二进制数有关。

It turns out, the closest float to 12.555 is actually 12.55500030517578125 while the closest double to 12.555 is 12.554999999999999715782905696. 事实证明,最接近12.555的浮点数实际上是12.55500030517578125,而最接近12.555的浮点数是12.554999999999999715782905696。 Notice how the double provides more accuracy, but the error is negative. 注意double如何提供更高的准确性,但错误是负面的。

At this point, it's probably now obvious why the round function goes up for float but down for double - they're both rounding to the closest decimal number to the underlying representation. 在这一点上,现在可能很明显为什么圆函数向上浮动而向下为双 - 它们都是四舍五入到底层表示的最接近的十进制数。

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

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