Babylonian方法递归异常:stackOverFlow

时间:2016-10-01 23:44:00

标签: java recursion

我编写代码以使用巴比伦方法获得一些平方根。

我询问用户的输入号码,然后询问用户的猜测。

public class JanghyupLee_H02 {

private double number;
private double guess;

public static void main(String[] args) {
    // TODO Auto-generated method stub

    String input;
    Scanner userInput = new Scanner(System.in);

    JanghyupLee_H02 AR = new JanghyupLee_H02();

    System.out.println("Type a number : ");
    input = userInput.next();

    if (input.equals("0") || input.equalsIgnoreCase("exit") || input.equalsIgnoreCase("no")) {
        System.exit(0);

    } else {

        AR.setNumber(Integer.parseInt(input));

    }

    System.out.println("Type your guess : ");
    input = userInput.next();

    if (input.equals("0") || input.equalsIgnoreCase("exit") || input.equalsIgnoreCase("no")) {
        System.exit(0);
    } else {

        AR.setGuess(Double.parseDouble(input));

        double newGuess = AR.getGuess();

        AR.testGuess(newGuess);

    }

}

public double getNumber() {
    return number;
}

public void setNumber(double inputNumber) {
    this.number = inputNumber;
}

public double getGuess() {
    return guess;
}

public void setGuess(double guessNumber) {
    this.guess = guessNumber;
}

public double testGuess(double guess) {
    double guessAcurracy = (getNumber() - (getGuess() * getGuess()));

     //exeption error here
    if ((guessAcurracy == 0) && (guessAcurracy <= 0.000005)) {
        System.out.println(guess);

        return guess;
    } else {

        setGuess((((0.5) * (getGuess() + getNumber() / getGuess()))));
        System.out.println(guess);
        System.out.println("---------------------");
        return testGuess(getGuess());
    }

}

}

基本上,guessAcuraccy是减去第一个输入,两个减去

计算输出。(这样答案越接近输入数字)

我有一个例外错误,

即使我写了||而不是&amp;&amp;。(实际上,||这不会递归)

  
    

线程中的异常&#34; main&#34; java.lang.StackOverflowError的         at sun.misc.FloatingDecimal $ BinaryToASCIIBuffer.dtoa(FloatingDecimal.java:431)         at sun.misc.FloatingDecimal $ BinaryToASCIIBuffer.access $ 100(FloatingDecimal.java:259)

  

我收到了这些异常错误,

请告诉我这里有什么问题。

1 个答案:

答案 0 :(得分:1)

这看起来很可疑:

double guessAcurracy = (getNumber() - (getGuess() * getGuess()));

要比较正方形,它应该是:

double guessAcurracy = (getNumber() * getNumber() - (getGuess() * getGuess()));

或更简单/通常/有效:

double guessAcurracy = Math.abs(getNumber() - getGuess());

这看起来也很可疑:

if ((guessAcurracy == 0) && (guessAcurracy <= 0.000005)) {
    // stop recursion

递归仅在guessAcurracy正好为零时才会停止,这对于浮点计算的结果来说非常不可能。

完全删除与零相等的测试。