java因子,使用Java中的递归的因子

I am learning Java using the book Java: The Complete Reference.

Currently I am working on the topic Recursion.

Please Note: There are similar questions on stackoverflow. I searched them but I didn't find the solution to my question. I am confused with the logic in the following program.

If I run the below program, it produces the correct output, but I didn't understand the logic.

I didn't understand the logic in the following line : result = fact(n-1) * n;

From my knowledge, If we pass the value of n=4 as shown in the below program,

Then, 3 * 4 is stored in the result i.e., 12.

Again, fact(n-1) is called. Then n becomes 3.

Then the 2 * 3 is stored in the result replacing the previous 12.

I think you understood where I am stuck up/confused.

Thank you.

class Calculation

{

int fact(int n)

{

int result;

if(n==1)

return 1;

result = fact(n-1) * n;

return result;

}

}

public class Factorial

{

public static void main(String args[])

{

Calculation obj_one = new Calculation();

int a = obj_one.fact(4);

System.out.println("The factorial of the number is : " + a);

}

}

解决方案

result is a local variable of the fact method. So each time the fact method is called, the result is stored in a different variable than the previous fact invocation.

So when fact is invoked with 3 as argument, you can imagine that its result is

result3 = fact(2) * 3

result3 = result2 * 3

result3 = 1 * 2 * 3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值