题解 | #求解立方根#

求解立方根

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

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main {

private static double split(double left, double right, double num) {
    double mid = (left + right) / 2;
    double res = 0.0;
    double value = mid * mid * mid;
    if (Math.abs(num - value) <= 0.001) {
        res = mid;
    } else if (value > num) {
        res = split(left, mid, num);
    } else if (value < num) {
        res = split(mid, right, num);
    }
    return res;
}
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    // 注意 hasNext 和 hasNextLine 的区别
    while (in.hasNextDouble()) { // 注意 while 处理多个 case
        double num = in.nextDouble();
        double anum = num;
        if (num < 0) {
            anum = 0 - anum;
        }
        

        double left = 0;
        double right = anum/2+1;
        double res = split(left, right, anum);

        if (num < 0) {
            System.out.print("-" + String.format("%.1f", res));
        }else{
            System.out.print(String.format("%.1f", res));
        }



    }
}

}

全部评论

相关推荐

05-09 12:23
已编辑
华南理工大学 Java
野猪不是猪🐗:给他装的,双九+有实习的能看的上这种厂我直接吃⑨✌们拿它练练面试愣是给他整出幻觉了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务