描述:

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

输入:

待求解参数 double类型

输出:

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

样例输入:

216

样例输出:

6.0


二、解题报告

本题要求一个数的立方根的*似值,精确到小数点后的一位。这里使用 牛顿迭代法 求*似值。

牛顿迭代法,又称为牛顿-拉夫逊(拉弗森)方法(Newton-Raphson method),它是牛顿在17世纪提出的一种在实数域和复数域上*似求解方程的方法。多数方程不存在求根公式,因此求精确根非常困难,甚至不可能,从而寻找方程的*似根就显得特别重要。方法使用函数的单根附*具有*方收敛,而且该法还可以用来求方程的重根、复根,此时线性收敛,但是可通过一些方法变成超线性收敛。另外该方法广泛用于计算机编程中。

的初始*似值:

  • 过点 的一次*似值。

  • 过点 的二次*似值。

  • 重复以上过程,得 次*似值,上式称为牛顿迭代公式


首先确定我们的函数

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

代码如下:

#include <iostream>
#include <iomanip>
using namespace std;
#define E 0.01

double f(double x, double num) // 函数
{
    return x*x*x-num;
}

double _f(double x)  // 导函数
{
    return 3*x*x;
}

double getCubeRoot(double input)
{
    double x0;  
    double r = 1;
    do
    {
        x0 = r;
        r = x0 - f(x0,input)/_f(x0);
    } while(f(r,input) > E || f(r,input) < -E);

    return r;
}

int main()
{
    double x;
    cin >> x;
    double result = getCubeRoot(x); 
    cout << fixed << showpoint << setprecision(1) << result << endl;
    return 0;
}







个人站点:http://songlee24.github.com

相关文章:

  • 2022-12-23
  • 2021-06-18
  • 2021-07-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-12
  • 2022-12-23
  • 2021-10-10
  • 2021-08-27
相关资源
相似解决方案