实际操作是在行返回中执行的
return (num == 1 ? 1 : num * firstFactorial(num - 1 ) );
我们如何获得 8 的 40320 ?
public class Factorial {
public static int firstFactorial(int num) {
return (num == 1 ? 1 : num * firstFactorial(num - 1 ) );
}
public static void main(String[] args) {
System.out.println(firstFactorial(8));
}
}
答案 0 :(得分:0)
该return语句中发生了很多事情。可以这样重写firstFactorial
函数:
public static int firstFactorial(int num) {
if (num == 1) {
return 1;
}
int decreased = num - 1;
int recursiveFactorial = firstFactorial(decreased);
int result = num * recursiveFactorial;
return result;
}
首先,这是使用称为 recursion 的技术。该函数使用number参数减小1进行调用。您可以这样想:
1. You call firstFactorial with value of 8
2. firstFactorial(8) calls itself with a value of 7
3. firstFactorial(7) calls itself with a value of 6
...
8. firstFactorial(2) calls itself with a value of 1
9. firstFactorial(1) returns 1 because of the if-statement
在调用自身之后,该函数将递归调用的返回值与自己的参数相乘并返回。因此它将继续这样:
10. firstFactorial(2) multiplies 1 with 2 and returns 2
11. firstFactorial(3) multiplies 2 with 3 and returns 6
10. firstFactorial(4) multiplies 6 with 4 and returns 24
...
14. firstFactorial(8) multiplies 5040 with 8 and returns 40320 to you
所有这些将计算出如下值的能力:8 * 7 * 6 * ... * 1
其余部分或多或少是编码风格和语法糖。 您不需要局部变量,只需一行即可执行调用和操作:
public static int firstFactorial(int num) {
if (num == 1) {
return 1;
}
return num * firstFactorial(num -1);
}
然后在Java(<cond> ? <true statement> : <false statement>
)中有一个三元条件运算符,它使您可以在一行中表示整个函数体:
public static int firstFactorial(int num) {
if (num == 1) {
return 1;
}
return (num == 1) ? 1 : (num * firstFactorial(num -1));
}