通过Java完整参考我陷入了递归。我打印中间结果以查看值的变化。我可以看到num的值将递减到1并返回1,之后num的值如何递增到3和4?有什么帮助吗?
class Recursion {
public int fact(int num){
int result;
if(num==1){
return 1;
}
System.out.println("Befor fact value of num is: "+num);//here ok!
result=fact(num-1)*num;
System.out.println("After value of num is: "+num); //here not ok!
//System.out.println("result= "+result);
return result;
}
public static void main(String[]args){
Recursion obj=new Recursion();
System.out.println(obj.fact(4));
}
}
答案 0 :(得分:4)
您似乎正在打印错误的变量,
System.out.println("Before fact value of n is: "+num);//here ok!
result=fact(num-1)*num;
// You didn't change "num".
System.out.println("After value of n is: "+result); //result, not num.
//System.out.println("result= "+result);
return result;
打印
Before fact value of num is: 4
Before fact value of num is: 3
Before fact value of num is: 2
After value of num is: 2
After value of num is: 6
After value of num is: 24
24
答案 1 :(得分:2)
每次调用一个事实方法时,Java都会将该调用保存在堆栈中,它也会保存num
变量的值,因为它是事实方法的局部变量。
由于您未更改num
值,因此发生的情况将如下:
call fact(4) > print: Befor fact value of n is: 4
Then call fact(3) > print: Befor fact value of n is: 3
Then call fact(2) > print: Befor fact value of n is: 2
并且自从Stack最后出现之后,发生的事情就像是:
continue with call of fact(2) > print: After value of n is: 2
Then continue with call of fact(3) > print: After value of n is: 3
Then continue with first call of fact(4) > print: After value of n is: 4