【中等】HJ107 求解立方根

https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca?tpId=37&tqId=21330&rp=1&ru=/exam/oj/ta&qru=/exam/oj/ta&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D3%26tpId%3D37%26type%3D37&difficulty=undefined&judgeStatus=undefined&tags=&title=

 

逼近试错法,没有灵魂的思路:

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

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

        boolean bflag = false;
        if (dbData < 0) {
            dbData = 0.0 - dbData;
            bflag = true;
        }

        Integer intData = dbData.intValue();

        int COUNT_MAX = 20;
        int start = 0;

        for(int i = 1; i <= COUNT_MAX;i++) {
            int p = i * i * i;
            int n = (i + 1) * (i + 1) * (i + 1);
            if(intData >= p && intData < n) {
                start = i;
                break;
            }
        }

        double ret = 10000000;
        double minGap = 10000000;
        // 逐步逼近.
        double step = 0.1;
        for (double m = start + 0.0;  m < (start + 1.0); m += step) {
            double temp = m * m * m;
            double gap = ((temp - dbData) >= 0) ? (temp - dbData) : (dbData - temp);
            if(minGap > gap) {
                minGap = gap;
                ret = m;
            }

        }
        DecimalFormat df = new DecimalFormat("0.0");
        if(bflag) {
            ret = 0.0 - ret;
        }
        System.out.println(df.format(ret));

    }
}
View Code

 

 

posted @ 2022-04-07 12:01  v大喵  阅读(43)  评论(0编辑  收藏  举报