计算一个数字的立方根,不使用库函数
详细描述:
接口说明
原型:
floatgetCubeRoot(float fInput);
输入参数:
float fInput//待求解参数
输出参数(指针指向的内存区域保证有效):
无
返回值:
Float //输入参数的立方根
方法一: 牛顿迭代法#include "OJ.h" #include <math.h> using namespace std; /* 功能: 计算一个数字的立方根 输入:float input 待求解参数 输出:无 返回:Float 输入参数的立方根 */ //float getCubeRoot(float fInput) //{ // /*在这里实现功能*/ // if (fInput == 0) return (double)0; // float pre = 0; // float res = 1; // while (fabs(res - pre) > 0.000001) // { // pre = res; // res = (2 * res + fInput / (res*res)) / 3; // 迭代公式 // } // // // return res; //} float getCubeRoot(float fInput) { const float x = fInput; float y = x; while (fabs(y - (2 * y / 3 + x / y / y / 3)) > 0.001) { y = 2 * y / 3 + x / y / y / 3; } return y; }
方法二:pow(math.h)
#include "OJ.h" #include <math.h> using namespace std; /* 功能: 计算一个数字的立方根 输入:float input 待求解参数 输出:无 返回:Float 输入参数的立方根 */ float getCubeRoot(float fInput) { /*在这里实现功能*/ float a = 0; a = pow((float)fInput,1.0/3); return a; }