如果我删除注释,代码工作正常,如果我注释上面的注释行,我会收到错误
package TEST;
class Fact {
// this is a recursive method
int fact(int n) {
// if (n == 1)
// return 1;
int result = fact(n - 1) * n;
return result;
}
public static void main(String args[]) {
Fact f = new Fact();
System.out.println("Factorial of 7 is " + f.fact(5));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
if i remove the comment the code is working fine and if i comment the above lines which are commentd i get an error
最佳答案
这是编写递归程序的两个条件。 1. 方法调用自身 2. 终止条件
当你评论
//if (n == 1)
//返回 1;
您的代码不知道何时终止并进入无限循环,因此出现错误。
关于java - 递归代码无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22316763/