有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用挤压定理在java中嵌套逼近平方根

嘿,伙计们,这是一个作业,这是我的头。我的老师正在很快地调动全班同学。这是我用java编写的第四个程序,我正在寻找一些建议。我需要找到一个数字的近似sqrt,它与我的程序中定义的ε误差成正比。然而,这需要使用挤压定理来完成,并不断更新我的边界。在java中,当变量在整个过程中使用时,如何流畅地更新变量的值?请记住,我的教授还没有返回值,所以我认为他不打算让我们使用它们。记住,我是个新手,但我思想开放

    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    final double EPSILON = .0000000001;


    System.out.print("Enter a number to find its square root -> ");
    double number = sc.nextDouble();
    double low = 0;
    double high = 0;
    double midPoint = (low+high)/2;
    high = number;
    double midPointSqr = midPoint*midPoint;
    if (number < 0) {
        System.out.println("NaN");
    } else {
        while ((Math.abs(midPointSqr - number)) > EPSILON) {


            {
                if (number <= 1) {
                    low = 0;

                    if (midPointSqr > number)
                    {
                        midPoint = (high+low)/2;
                        high = high/2;
                     System.out.printf("%.6f, %.6f\n", low, high);
                    }
                    else
                    {
                       midPoint = (high+low)/2;
                       low = high/2;
                        System.out.printf("%.6f, %.6f\n", low, high);
                    }


                } else {
                    low = 1;

                     if (midPointSqr > number)
                    {
                        midPoint = (high+low)/2;
                        high = high/2;
                     System.out.printf("%.6f, %.6f\n", low, high);
                    }
                    else
                    {
                       midPoint = (high+low)/2;
                        low = high/2;
                        System.out.printf("%.6f, %.6f\n", low, high);
                    }

                }
            }
        }
    }

}

}


共 (1) 个答案

  1. # 1 楼答案

    无论何时更新中点变量,都需要更新中点SQR变量。所以无论你在哪里有赋值语句,比如

    midPoint = <something>;
    

    在这之后,你应该像这样重新计算你的方块:

    midPointSqr = midPoint * midPoint
    

    另一个交替点是在任何地方使用函数,而不是使用中点SQR变量

    double getSqr(double value){
         return value* value;
    }
    

    因此,无论您在何处使用midPointSqr变量,都应将其替换为以下方法代码:

    getSqr(midPoint)