简体   繁体   English

为什么会出现Stackoverflow错误?

[英]Why do I get a Stackoverflow Error?

I have a little recursive algorithm which should guess a number. 我有一个递归算法,应该猜一个数字。 I call the method guessNumber and give a number and a lower value than the number and a higher value than the number. 我调用方法guessNumber,并给出一个数字和一个比该数字低的值,以及一个比数字高的值。 If the value is higher than the middle of area of numbers then it makes the same process for the new area of numbers. 如果该值高于数字区域的中间值,则对新的数字区域进行相同的处理。 But it the value is lower it makes the same with the lower area of numbers. 但是它的值越小,数字面积越小。 And if none of these cases is true then it returns the max value (it could be the min value because they're the same at this point). 如果所有这些情况都不成立,则返回最大值(可能是最小值,因为此时它们是相同的)。 But why gives that an StackOverflowError? 但是为什么要给出一个StackOverflowError? I don't see why the programm can't end. 我不明白为什么程序无法结束。 Any help would be appreaciated. 任何帮助将不胜感激。 Thank you. 谢谢。

public class Starter {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Starter s = new Starter();
    System.out.println(s.guessNumber(18, 1, 100));
}

public int guessNumber(int num, int min, int max) {
    int middle = (max - (min - 1)) / 2;
    if (num > middle) {
        guessNumber(num, middle + 1, max);
    } else if (num < middle) {
        guessNumber(num, min, middle);
    }
    return max;
}
}

Now I don't get an error anymore with this code: 现在,此代码不再出现错误:

public int guessNumber(int num, int min, int max) {
int middle = (max + min) / 2;
if (num > middle) {
    return guessNumber(num, middle + 1, max);
} else if (num < middle) {
    return guessNumber(num, min, middle);
}
return max;
}

But the number isn't correct. 但是这个数字不正确。 If i call it this way guessNumber(18, 1, 100) the expected output should be 18 but i get 19 . 如果我用这种方式来guessNumber(18, 1, 100)guessNumber(18, 1, 100)的预期输出应该是18但我得到19 And if i call it this way guessNumber(34, 1, 100) then the ouput is 37 如果我这样称呼guessNumber(34, 1, 100)则输出为37

First of all, you forgot to return the value of the recursive calls. 首先,您忘记了返回递归调用的值。

Second of all, your calculation of middle is wrong. 其次,您对middle位数的计算是错误的。 For example, if min is 10 and max is 20, your calculation will assign 5 to middle , instead of 15. 例如,如果min为10且max为20,则您的计算会将5分配给middle ,而不是15。

public int guessNumber(int num, int min, int max) {
    if (min == max) {
        return min;
    }
    int middle = (max + min) / 2;
    if (num > middle) {
        return guessNumber(num, middle + 1, max);
    } else {
        return guessNumber(num, min, middle);
    }
}

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

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