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

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);

}

最佳答案

您的结果不可能达到最终条件,因为乘以数字不太可能产生确切的数字,您必须引入误差范围,因为平方根通常不精确,并且由于浮点数的限制,浮点运算使用近似值。

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;
}

07-26 04:29