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);
}
}
}
我得到这个异常:
Exception in thread "main" java.lang.StackOverflowError
at hello.findP(hello.java:12)
at hello.findP(hello.java:19)
当我尝试在 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
最佳答案
尝试将 sum == 1000
更改为 sum >= 1000
。没有总和正好 1000 的三元组,因此它跳过了终止条件。
此外,您的 Ruby 代码与您的 Java 代码不匹配(您缺少 else
)。即使它确实找到了 1000 的总和,它也会打印消息,并继续递归直到它崩溃。
关于java - 此递归中的 Stackoverflow 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3747790/