牛客网 - 在线编程 - 华为机试 - 求解立方根

题目描述

•计算一个数字的立方根,不使用库函数

详细描述:

•接口说明

原型:

public static double getCubeRoot(double input)

输入:double 待求解参数

返回值:double  输入参数的立方根,保留一位小数

输入描述:

待求解参数 double类型

输出描述:

输入参数的立方根 也是double类型

示例1

输入

216

输出

6.0

c++:

总体思想:牛顿法

<iomanip>控制输出格式,setprecision()控制精度,fixed:浮点数以定点格式(小数形式)输出

注意:while条件fabs

#include<iostream>
#include<math.h>
#include<iomanip>
using namespace std;

double getCubeRoot(double );
int main()
{
    double a;
    while(cin >> a)
    {
        double b = getCubeRoot(a);
        cout << setprecision(1) << fixed <<b;
    }
    return 0;
}
double getCubeRoot(double a)
{
    double b = 1;
    while( fabs(pow(b,3) - a) > 1e-7)
    {
        b -= (pow(b,3) - a) / (3 * pow(b,2));
    }
    return b;
    
}

python:

a = float(input())
b = 1
while abs(b ** 3 - a) > 1e-7:
    b -= (b ** 3 - a) / (3 * b ** 2)
print("%.1f" %b)

猜你喜欢

转载自blog.csdn.net/qq_39735236/article/details/81775744