我试图理解 Java 中的递归方法,并尝试了这种简单的方法来计算阶乘。不知何故,它不起作用。有人能告诉我为什么吗?
public class FactorialRecursive extends ConsoleProgram {
public void run() {
println("This program calculates the factorial of an integer n.");
int n = readInt("Please insert n: ");
int result = factorial(n);
println("The factorial of " + n + " is " + result);
}
private int factorial(int n) {
int total;
if (n == 1) total = 1;
total = n * factorial(n - 1);
return (total);
}
}