华为OJ(求解立方根)

描述:

  • 计算一个数字的立方根,不使用库函数。
  • 函数原型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)(xx0) ,求出L与x轴交点的横坐标  x1=x0f(x0)f(x0) ,称  x1 为  r  的一次近似值。

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

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


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

f(x)=x3m

其中  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;
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值