简体   繁体   English

递归方法和堆栈溢出

[英]Recursive method and stack overflow

Okay so I have an assignment to determine how long will it take to a monkey to climb a pole of x height. 好的,所以我有一个任务来确定一只猴子爬上x高度的杆需要多长时间。 If ascends 10 ft. in 10 minutes and slips down 3 in 10 min while resting. 如果在10分钟内上升10英尺,在休息时在10分钟内滑落3英尺。 When it reaches the top of the pole it stops, and climbs one feet per minute. 当它到达杆的顶部时它停止,并且每分钟爬上一英尺。 This using recurssion, and my method is right so far, but I'm getting stack overflow and I do not know how to avoid it so im freakin out, any idea? 这是使用recurssion,我的方法是正确的,但我得到堆栈溢出,我不知道如何避免它所以即时通讯,任何想法?

Thanks guys 多谢你们

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

    } } }

You can't do it like that. 你不能这样做。 You might have problems with this two lines: 这两行可能有问题:

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

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

If you're having the case that time is for example 10, you're adding 10 to the time-var and its finally 20, so 20 % 10 will result a true once again :) 如果您遇到的情况是时间是例如10,那么您将为时间变量添加10并且最终为20,因此20%10将再次成为真实的:)

Edit:\\ 编辑:\\

Damn, just a bit too late :) 该死的,有点太晚了:)

Another edit:\\ 另一个编辑:

To avoid this problem, add a reminder to the parameters: 要避免此问题,请为参数添加提醒:

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

You can call it with now like that: 您可以像现在这样调用它:

Climb(1800, 0, true);

Might be some mistakes in it, but hope its you anyway. 可能会有一些错误,但无论如何都希望你。

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. 它可能会解决这个问题。

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

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