简体   繁体   English

没错! 找不到带有java.lang.StackOverflowError的解决方案

[英]No error! Can't find the solution with java.lang.StackOverflowError

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

Please someone help me to solve this. 请有人帮我解决这个问题。 I am being tired of doing this for many time. 我已经厌倦了很多时间。

You never change root and num , and you reset guess in each call to guess= num/(root+1); 你永远不会改变rootnum ,且您重置guess在每次调用guess= num/(root+1); , so you get an endless recursion, leading to StackOverflowError . ,因此您将获得无尽的递归,从而导致StackOverflowError

I'm not sure what the correct logic should be, but to prevent the endless recursion you must either pass different values of root or num to each recursive call, or don't reset guess at the start of the method. 我不确定正确的逻辑是什么,但是为了防止无休止的递归,您必须将rootnum不同值传递给每个递归调用,或者不要在方法开始时重置guess

I got my answer myself. 我自己得到了答案。 Asking for a guess will solve the problem. 问一个猜测将解决问题。 Do not need to set the guess like the code I have given. 不需要像我给出的代码那样进行猜测。 However, I do not know the reason but it solved the problem. 但是,我不知道原因,但是它解决了问题。 Thank you. 谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM