Home  >  Q&A  >  body text

关于C++ printf()函数的一点疑问

初学C++,对于printf()函数的精度指示符有一点疑问。

因为之前学过其他语言,所以在解决四舍五入的问题的时候使用了printf()函数,但是发现:

float x=20.095;
printf("%.2f",x);

这样输出的是20.09,而不是正常四舍五入的20.10。
但如果是另一种情况:

float x=20.085;
printf("%.2f",x);

20.09就能够正常的输出

请教一下,这是因为什么原因导致的?搜索了一下没有找到相关的说明,书上也没有具体解释。
如果想要正常的四舍五入,对于初学者,比较简单的解决方案是什么?
谢谢!

伊谢尔伦伊谢尔伦2764 days ago549

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-04-17 12:10:39

    is not a problem with printf(), it is a problem with precision. 20.085 is not precise in computer memory. In fact, this value cannot be accurately expressed in binary. The first few dozen digits of its decimal part are 0.00010101110000101000111101011100001010001111011, which has already exceeded the precision of float. Therefore, it will be stored as an approximate value. Unfortunately, this approximate value is a little smaller than 20.085, so it will naturally be rounded off.
    You can read this article: http://www.cnblogs.com/antineutrino/p/4525224.html

    reply
    0
  • Cancelreply