C++中的四舍五入

来源:互联网 发布:js密码加密 编辑:程序博客网 时间:2024/05/21 21:01
转自:http://blog.csdn.net/flyingstarwb/article/details/2737451
1.整数法 a为需要进行四舍五入的整数 result = int (a+0.5);
2.小数法,a为需要进行四舍五入的整数,count为需要精确的位数(>0)
  float temp = count*10.0;
  result = (int (a*temp + 0.5) )/ temp;

后面的评论,需要注意,需要自己进一步验证。
需要加上一个前提:a是正数。
此外,小数法中
float temp = count*10.0;
应修改为:
double temp = pow(10, count);

转自:http://blog.csdn.net/hankai1024/article/details/7887415
oor : 不大于自变量的最大整数             2                2                  -3                  -3  ceil   :不小于自变量的最大整数             3                3                  -2                  -2  round:四舍五入到最邻近的整数               2                3                  -2                  -3    floor(),ceil() 需包含头文件<math.h>    C++中没有直接的round函数 需自己建立  double round(double r)  {      return (r > 0.0) ? floor(r + 0.5) : ceil(r - 0.5);  }  




0 0