0

好的,所以我有一个任务来确定一只猴子爬 x 高度的杆子需要多长时间。如果在 10 分钟内上升 10 英尺,在休息时在 10 分钟内滑落 3 英尺。当它到达杆子的顶部时,它会停下来,并以每分钟一英尺的速度爬升。这使用递归,到目前为止我的方法是正确的,但是我遇到了堆栈溢出,我不知道如何避免它,所以我吓坏了,知道吗?

多谢你们

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

    } } }
4

2 回答 2

1

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

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

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

如果您遇到时间为 10 的情况,则将 10 添加到 time-var 中,最后为 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);

Might be some mistakes in it, but hope its you anyway.

于 2013-10-17T05:49:54.287 回答
1

Stack error occurs when the memory is filled up, ie the problem here is that you don't have a working exit statement.

Try change this to long

if (height <= 0L) 

It would probably solve the issue.

于 2013-10-17T06:02:45.347 回答