题解 | #求解立方根#

求解立方根

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

二分法

注意结果精度只保留一位 和 输入为负数时



import java.util.Scanner;


public class Main {
    public static void main(String[] args) {
               Scanner scanner = new Scanner(System.in);
        double input = scanner.nextDouble();

        double num= input>0? input:-input; //负数 当正数来处理

        double bottom = 0;
        double top = 0;
        while (top * top * top < num) {  // 比如 5 介于 1^3  和 2^3之间
            top++;
        }
        bottom = top - 1;

        double mid = bottom + (top - bottom) / 2;
        double mul = mid * mid * mid;

        while(top - bottom > 0.1){  // 因为只保留一位小数
            if (mul > num) {
                top = mid;
            } else if (mul < num) {
                bottom = mid;
            }

            mid = bottom + (top - bottom) / 2;
            mul = mid * mid * mid;
        }

        
        if(input<0){// 原数为负,结果也应该为负
            mid=-mid;
        }
        System.out.println(String.format("%.1f",mid));  //  12  => 2,3      -5 ==> -1.7

    }
}

全部评论
代码貌似有点问题,输入3.375(1.5^3),死循环。二分法while中的代码没有判断mul=num的情况
3 回复
分享
发布于 2022-05-27 20:05
点赞 回复
分享
发布于 2022-03-11 08:51
联想
校招火热招聘中
官网直投
66666666666
点赞 回复
分享
发布于 2022-03-23 22:54
这才是不用库 6666
点赞 回复
分享
发布于 2022-04-07 01:31

相关推荐

19 4 评论
分享
牛客网
牛客企业服务