java求一个整数的平方根,不保留小数

碰到一个面试题:

 public static void main(String[] args) {

//        questionOne(3);
    }

    //  1.  java求一个整数的平方根,不保留小数
    public static void questionOne(int sc) {
        //保留几位小数
        DecimalFormat df = new DecimalFormat("0");
        System.out.print(sc + "的算术平方根是:");
        System.out.println(df.format(SQR(sc)));
    }

    public static double SQR(int a) {
        double x1 = 1, x2;
        //牛顿迭代公式
        x2 = x1 / 2.0 + a / (2 * x1);
        while (Math.abs(x2 - x1) > 1e-4) {
            x1 = x2;
            x2 = x1 / 2.0 + a / (2 * x1);
        }
        return x2;
    }

转:https://www.cnblogs.com/hezhiyao/p/7544593.html

posted @ 2019-04-12 19:26  你就像甜甜的益达  阅读(190)  评论(0编辑  收藏  举报