正文

Round Number 辑合2012-02-01 23:58:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/katwood/53216.html

分享到:

之一  From C-FAQ  Question 14.6 How do I round numbers?
http://c-faq.com/fp/round.html

The simplest and most straightforward way is with code like

(int)(x + 0.5)
C's floating to integer conversion truncates (discards) the fractional part, so adding 0.5 before truncating arranges that fractions >= 0.5 will be rounded up. (This technique won't work properly for negative numbers, though, for which you could use something like (int)(x < 0 ? x - 0.5 : x + 0.5), or play around with the floor and ceil functions.)

You can round to a certain precision by scaling:

 (int)(x / precision + 0.5) * precision
Handling negative numbers, or implementing even/odd rounding, is slightly trickier.

Note that because truncation is otherwise the default, it's usually a good idea to use an explicit rounding step when converting floating-point numbers to integers. Unless you're careful, it's quite possible for a number which you thought was 8.0 to be represented internally as 7.999999 and to be truncated to 7.


之二 From 忆向Blog
http://www.hustyx.com/2010/69

之三 自我总结帖 
http://blog.pfan.cn/katwood/53215.html

阅读(1238) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册