四舍五入算法

来源:互联网 发布:windows 7 ie11 编辑:程序博客网 时间:2024/04/23 16:42

求数值四舍五入后的值最好的方法INTI0.5)INT函数是相当于舍弃小数位的函数,将浮点数在数轴上向左移动找最接近的整数,找到后+0.5进行取正运算;

 

所述,使用INT函数将原有的数字进行+0.5然后取整。

1:用递归算法求解如下,

#include "stdafx.h"

#include "math.h"

/*

// 使用递归函数,求一个数值的四舍五入值

*/

int parseData(double value, int digite)

{

     if(digite == 0)                                              // 末尾加0.5

     {

         return ((int)(value += 0.5));

     }

     else                                                             // 继续取正

     {

         return (parseData(value*10,--digite));

     }

}

 

/*

// 使用递归函数,求一个数值的四舍五入值

*/

double Round(double value , int digite)

{

     int iValue = parseData(value,digite);

     int iPub = pow(10,digite);// 10digite平方

     return ((double)(iValue)/iPub);// 返回小数点精确位。精确位以后的数字舍弃,不准确。

}

 

int main(int argc, char* argv[])

{

     double dd = 0.125657;

     dd = Round(dd,3);

     cout << dd << endl;

     system("pause");

     return 0;

}

需要包括math.h;

编译环境:VC7.0

原创粉丝点击