正文

Round Or Omit2012-02-01 23:57:00

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

分享到:

float aver;
int sum, n;
aver=sum/n;

We get the omit one.

float aver;
int sum, n;
aver=(float)sum/n;  //(In fact , it is ' (float)(sum) / n; ')

We get the round one.


Assign value directly -> omit
int a;
float b;
b=3.51;
a=b;
print a and we get 3

And  '(int)float_number' also get the omitted one

!!! But use '%.f' we get the round one!!! 
According to the C-FAQ 14.6, the simplest and most straightforward way to round number is to use this:
' (int)(x+0.5); '
However, it can be used to round number for positive numbers but not for negative ones.
So a better one is:
' (int)(x<0? x-0.5 : x+0.5) '

To round to a certain precision by scaling:
' (int)(x / precision + 0.5)*precision

阅读(1189) | 评论(0)


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

评论

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