[英]Need help deciphering a factorial code in Java
我已经看到了使用for循环的答案,我理解,但是我最近遇到了这个代码,我不知道它是如何工作的。
public class learn {
public static int factorial (int N){
if (N<=1 ) return 1; // won't this mean that "1" is returned at the end all the time?
else return (N*factorial (N-1)); /* since there's no variable storing the sum
I don't get how this is working out either,
won't it just be returned and lost?*/
}
public static void main(String[] args) {
System.out.println(factorial(4));
}
}
来自python背景,所以也许我误解了java中的返回... [编辑]似乎return 1
也是用Python编写的,所以它可能不是语言问题,我只是不知道递归函数如何结束 (我了解过程如何进行 - 它是一个自称的函数)。
以下是我如何解释此代码(错误地)的说明:
factorial(4)
被称为 else
语句将运行 - 4*factorial(3)
factorial(3)
被调用 - else
语句再次运行 - 3*factorial(2)
factorial(2)
被称为 - 2*factorial(1)
。 此时,我们有4 * 3 * 2 * 1,但代码仅在if (N<=1) return 1
行停止的事实意味着if (N<=1) return 1
而不是总和权利? (我显然错了,因为控制台打印了正确的数字24
) 这不意味着“1”总是在最后返回吗?
不,当N
小于1时,它将仅返回1.(根据您的条件, if (N<=1 ) return 1;
)对于所有其他情况,它将递归递归。
因为没有变量存储总和我不知道这是如何工作的,它不会只是返回和丢失?
当一个方法返回时,它退出当前方法并返回到调用点并从那里继续 。 为简单起见,请采用以下方案:methodA调用methodB,methodB调用methodC:
public void methodA(){
print("entering method A.."); //(1)methodA invoked..
methodB(); //(2)call methodB
print("exiting method A"); //(8)exit from methodB, continue from here
}
public void methodB(){
print("entering method B.."); //(3)mthodB invoked..
methodC(); //(4)call methodC
print("exiting method B"); //(7)exit from methodC, continue from here. exit methodB
}
public void methodC(){
print("entering method C.."); //(5)methodC invoked..
print("exiting method C"); //(6)exit methodC, continue from whoever called methodC
}
您将获得如下结果:
entering method A..
entering method B..
entering method C..
exiting method C
exiting method B
exiting method A
如果你能理解方法A和C的程序流程。现在尝试理解一个叫做“本身”的方法。
//Let say N is 3..
public static void main(String[] args){
factorial(3); //(9)
}
public static int factorial (int N) //(1)N:3, (3)N:2, (5)N:1
{
if (N<=1 )
return 1; //(6)Ret 1, return and continue from whoever called me
else
return (N*factorial (N-1)); //(2), (4), (7)Ret 2*1, (8)Ret 3*2*1
}
在(6),它通过返回1退出方法并从调用该方法的地方继续。 它所在的地方是(7)。
在(7),它通过返回N * 1(2 * 1 = 2)退出该方法并从调用该方法的地方继续。 它被调用的地方是(8)。
在(8),它通过返回N * 2(3 * 2 = 6)退出该方法并从调用该方法的地方继续。 它被称为的地方是(9)这是主要的方法。
如果参数N
等于或小于1,则if语句仅返回1,否则将执行else子句。 在else子句中,由于它返回参数N
的乘积和factorial(N-1)
的返回值,因此Java需要等待factorial(N-1)
返回一个值才能进行乘法并返回值。 不需要将参数N
的值存储到字段中,因为参数也是变量,只是它的值从方法的调用者传递。
在您的代码中, factorial
被调用4次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.