华为机试 HJ107 题解 | #求解立方根#

求解立方根

https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca

#include <iostream>
#include <cmath>
#include <iomanip>
// #include <bits/stdc++.h>
using namespace std;

// 获取一个实数的立方根
double GetSqrt3(double a) {
    double eps = 0.00001;
    double res = a;
    double left = 0.0;
    double right = a;
    if (abs(a - 1.0) <= eps) {
        return 1.0;
    } else if (a > 1.0) {
        // res 结果在 [1.0,a)之间
        double left = 1.0;
        double right = a;
        while (left < right) {
            double mid = (left + right) / 2;
            double y = mid * mid * mid;
            if (abs(y - a) <= eps) {
                res = mid;
                break;
            } else if (y > a) {
                right = mid;
            } else if (y < a) {
                left = mid;
            }
        }
    } else if (a < 1.0) {
        // res 结果在(a, 1.0)之间
        double left = a;
        double right = 1.0;
        while (left < right) {
            double mid = (left + right) / 2;
            double y = mid * mid * mid;
            if (abs(y - a) <= eps) {
                res = mid;
                break;
            } else if (y > a) {
                right = mid;
            } else if (y < a) {
                left = mid;
            }
        }
    }

    return res;
}

int main() {
    double dVal;
    while (cin >> dVal) { // 注意 while 处理多个 case
        int flag = dVal > 0 ? 1 : -1;
        double dVal2 = abs(dVal);
        double result = GetSqrt3(dVal2);
        result = result * flag;
        cout << setprecision(1) << fixed << result << endl;
    }

    return 0;
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
昨天 10:46
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务