其他分享
首页 > 其他分享> > 求解立方根 (HJ107)

求解立方根 (HJ107)

作者:互联网

一:解题思路

这道题目和 leetcode69 题,求解x的平方根有些类似。都是采用二分的思想来做,可以对比分析。 

二:完整代码示例 (C++版和Java版)

C++:

#include <iostream>

using namespace std;

double getCubeRoot(double input)
{
    double low = 0;
    double high = input;

    while ((high-low)>=0.001)
    {
        double mid = low + (high-low) / 2;
        double mid3 = mid * mid*mid;
        if (input == mid3) return mid;
        else if (mid3 > input) high = mid;
        else low = mid ;
    }

    return high;
}

int main() 
{
    cout.precision(2);
    double x = 0;

    while (cin >> x)
    {
        cout << getCubeRoot(x) << endl;
    }

    return 0;
}

 

标签:求解,double,mid,mid3,high,立方根,low,input,HJ107
来源: https://www.cnblogs.com/repinkply/p/13381997.html