递归方法和堆栈溢出

时间:2013-10-17 05:32:49

标签: java recursion

好的,所以我有一项任务,要确定一只猴子爬上x高度的杆需要多长时间。如果在10分钟内上升10英尺,在休息时在10分钟内滑落3英尺。当它到达杆的顶部时它停止,并且每分钟爬上一英尺。这是使用recurssion,我的方法到目前为止,但我得到堆栈溢出,我不知道如何避免它,所以我freakin out,任何想法?

谢谢你们

public static long climb(long height, long time) {    //Recursive method

    if (height <= 0)     //base case
        return time;

/*Every 10 min add 3 to height (notice im doing it backwards, 
instead of substracting 3.
I find it easier to deal with this way and easier to implement the base case) *//

    else if (time != 0 && time % 10 == 0) {    

        return climb(height+3, time+10);
    }

    else  {
        return climb(height-1, time+1);

    } } }

2 个答案:

答案 0 :(得分:1)

你不能这样做。这两行可能有问题:

else if (time != 0 && time % 10 == 0) {    

    return climb(height+3, time+10);
}

如果您的情况是时间是例如10,那么您将在时间变量中添加10并且最终为20,因此20%10将再次成为真实:)

编辑:\

该死的,有点太晚了:)

另一个编辑:\

要避免此问题,请为参数添加提醒:

    public static long Climb(long height, long time, bool justrested)
    {
        //Recursive method
        if (height <= 0)
        {
            //base case
            return time;
        }

        if(time%10 == 0 && !justrested)
        {
            return Climb(height + 3, time + 10, true);
        }

        return Climb(height - 1, time + 1, false);
    }

您可以像现在这样调用它:

Climb(1800, 0, true);

可能会有一些错误,但无论如何都希望你。

答案 1 :(得分:1)

  内存填满时出现

Stack 错误,即此处出现问题   是你没有工作退出声明。

尝试将此更改为长

if (height <= 0L) 

这可能会解决问题。