此递归中的Stackoverflow错误

zen*_*ngr 2 ruby java recursion

Java中的这种递归出了什么问题?

public class findPyt
{
    public static int sum = 0;
    public static void main(String[] args)
    {
        findP(3, 4, 5);
    }

    public static void findP(int a, int b, int c)
    {
        sum = a+b+c;

        if (sum == 1000)
        {
            System.out.println("The Triplets are: "+ a +","+ b +","+ c);
        }
        else
        {
            findP(a*2, b*2, c*2);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到这个例外:

Exception in thread "main" java.lang.StackOverflowError
    at hello.findP(hello.java:12)
    at hello.findP(hello.java:19)
Run Code Online (Sandbox Code Playgroud)

当我尝试在Ruby中做同样的事情时,我得到了这个:

SystemStackError: stack level too deep


def pythagoreanTriples(a=3, b=4, c=5)

    if (a+b+c) == 1000
      puts "The Triplets are: "+ a +","+ b +","+ c
    else
    pythagoreanTriples(a*2, b*2, c*2)
    end
end
Run Code Online (Sandbox Code Playgroud)

zil*_*n01 12

尝试sum == 1000改为sum >= 1000.没有三倍款项正好 1000,因此它跳过的终止条件.

此外,您的Ruby代码与您的Java代码不匹配(您丢失了else).即使它确实找到1000的总和,它也会打印消息,并一直递归直到它崩溃.