您的位置:首页 > 其它

华为OJ(求解立方根)

2015-08-18 12:04 246 查看
描述:

计算一个数字的立方根,不使用库函数。
函数原型
double getCubeRoot(double input)


输入:

待求解参数 double类型

输出:

输出参数的立方根,保留一位小数

样例输入:
<code class="hljs  has-numbering" style="display: block; padding: 0px; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal; background: transparent;">216</code><ul class="pre-numbering" style="box-sizing: border-box; position: absolute; width: 50px; top: 0px; left: 0px; margin: 0px; padding: 6px 0px 40px; border-right-width: 1px; border-right-style: solid; border-right-color: rgb(221, 221, 221); list-style: none; text-align: right; background-color: rgb(238, 238, 238);"><li style="box-sizing: border-box; padding: 0px 5px;">1</li></ul>


样例输出:
<code class="hljs  has-numbering" style="display: block; padding: 0px; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal; background: transparent;">6.0</code><ul class="pre-numbering" style="box-sizing: border-box; position: absolute; width: 50px; top: 0px; left: 0px; margin: 0px; padding: 6px 0px 40px; border-right-width: 1px; border-right-style: solid; border-right-color: rgb(221, 221, 221); list-style: none; text-align: right; background-color: rgb(238, 238, 238);"><li style="box-sizing: border-box; padding: 0px 5px;">1</li><li></li></ul>
常见的用牛顿迭代法,即可解决。

设 r 是的根,选取 x0 作为 r 的初始近似值:

过点(x0,f(x0))做曲线y=f(x)的切线L,L的方程为 y=f(x0)+f′(x0)(x−x0),求出L与x轴交点的横坐标 x1=x0−f(x0)f′(x0),称 x1为 r 的一次近似值。

过点 (x1,f(x1)) 做曲线 y=f(x) 的切线,并求该切线与x轴交点的横坐标 x2=x1−f(x1)f′(x1),称 x2 为 r 的二次近似值。

重复以上过程,得 r 的近似值序列。其中, xn+1=xn−f(xn)f′(xn) 称为 r 的 n+1 次近似值,上式称为牛顿迭代公式。

首先确定我们的函数 f(x):

f(x)=x3−m

其中 m 是一个常数,程序的输入。求导函数:

f′(x)=3x2

#include<iostream>
#include<iomanip>
using namespace std;
double getCubeRoot(double);
const double err=0.01;
int main()
{
double m;
cin>>m;
double result = getCubeRoot(m);
cout << fixed << showpoint << setprecision(1) << result << endl;
//system("pause");
return 0;
}
double getCubeRoot(double m)
{
double x0,xn=1;
double y=xn*xn*xn;
while(y-m>err||y-m<-err)
{
x0=xn;
xn=x0-(x0*x0*x0-m)/(3*x0*x0);
y=xn*xn*xn;
}
return xn;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: