【问题标题】:No error! Can't find the solution with java.lang.StackOverflowError没有错误!找不到 java.lang.StackOverflowError 的解决方案
【发布时间】:2016-07-23 14:54:25
【问题描述】:
import java.util.*;

public class NRootx {

    public static Double NRmethod (Double num, int root, Double guess){
        guess= num/(root+1); //first guess  

        Double guess_output=1.0;

        for (int i=1;i<=root; i++)
        {
            guess_output *= guess;
        }

        Double error= guess_output-num;
        error = error * 0.001;
        guess = guess - error;

        if (Math.abs(error)>=0.000001)
            return NRmethod(num, root, guess); //Recursion 
        else
            return guess;

           //I can't find out the problem now. Java.lang.StackOverFlow error is showing. 

        }
    }
}

// Main function 
public static void main(String[] args) {

    Double x;
    int n;
    Scanner sc= new Scanner (System.in);
    System.out.println("Enter the value of x: ");
    x=sc.nextDouble();
    System.out.println("Enter the value of n: ");
    n=sc.nextInt();
    Double guess=x/(n+1);
    Double ans= NRmethod(x,n,guess);
    System.out.println("The value of y is ="+ans);
}

请有人帮我解决这个问题。我厌倦了这样做很多次。

【问题讨论】:

  • StackOverflowError问题无关,但使用double而不是Double,所以你不需要创建不必要的Double对象。
  • 还有:guess_output = Math.pow(guess, root);,不需要 for 循环。

标签: java recursion newtons-method


【解决方案1】:

您永远不会更改 rootnum,并且在每次调用 guess= num/(root+1); 时都会重置 guess,因此您会得到无限递归,从而导致 StackOverflowError

我不确定正确的逻辑应该是什么,但为了防止无休止的递归,您必须将 rootnum 的不同值传递给每个递归调用,或者不要在方法的开始。

【讨论】:

  • 哦,谢谢。这就是为什么我提倡用户给予猜测的价值。
【解决方案2】:

我自己得到了答案。要求猜测将解决问题。不需要像我给出的代码那样设置猜测。但是,我不知道原因,但它解决了问题。谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    相关资源
    最近更新 更多