gpt4 book ai didi

java - 计算平方根和立方根的递归算法

转载 作者:搜寻专家 更新时间:2023-11-01 01:01:32 25 4
gpt4 key购买 nike

当我运行我的代码时,有时可以正常工作,但其他时候我会收到此错误:

Exception in thread "main" java.lang.StackOverflowError       
at squareroot.SquareRoot.GetSquareRoot (SquareRoot.java: 9)
at squareroot.SquareRoot.GetSquareRoot (SquareRoot.java: 13)
at squareroot.SquareRoot.GetSquareRoot (SquareRoot.java: 13)`

我正在检查我的代码,但没有进入无限循环,请问我该如何解决这个问题?谢谢。

public static double GetSquareRoot(double n, double low, double high) {
double sqrt = (low + high) / 2;
if (sqrt*sqrt > n)
return GetSquareRoot(n, low, sqrt);
if (sqrt*sqrt < n)
return GetSquareRoot(n, sqrt, high);
return sqrt;
}
public static double Sqrt(double n){
return GetSquareRoot(n, 0, n);
}

public static double GetCubicRoot(double n, double low, double high) {
double cbrt = (low + high) / 2;
if (cbrt*cbrt*cbrt > n)
return GetCubicRoot(n, low, cbrt);
if (cbrt*cbrt*cbrt < n)
return GetCubicRoot(n, cbrt, high);
return cbrt;
}
public static double Cbrt(double n) {
return GetCubicRoot(n, 0, n);
}

public static void main(String[] args) {
Scanner Input = new Scanner(System.in);

double n = Input.nextDouble();
double sqrt = Sqrt(n);
double cbrt = Cbrt(n);

System.out.println("Raiz cuadrada igual a: "+ sqrt);
System.out.println("Raiz cubica igual a: "+ cbrt);

}

最佳答案

您的结果永远不可能达到结束条件,因为将数字相乘不太可能产生准确的数字,您必须引入误差范围,因为平方根通常不精确,并且 float 算术由于 float 而使用近似值积分限制。

public static double GetSquareRoot(double n, double low, double high) {
double errorMargin = 0.001;
double sqrt = (low + high) / 2;
double diff = sqrt*sqrt - n;
if ( diff > errorMargin)
return GetSquareRoot(n, low, sqrt);
if ( -diff > errorMargin)
return GetSquareRoot(n, sqrt, high);
return sqrt;
}

关于java - 计算平方根和立方根的递归算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15147184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com