我写了一个Factorial程序。我已经完成了整个程序,它运行没有任何问题。 但是,我希望输出看起来像这样
Begin Factorial Program. . .
Provide number and the factorial will be computed: 4
4! is . . .
In f(4) and calling f(3) . . .
In f(3) and calling f(2) . . .
In f(2) and calling f(1) . . .
In f(1) and calling f(0) . . .
In f(0) and computing f(0). Returning 1
f(1) is 1 * 1 which equals 1. Returning
f(2) is 2 * 1 which equals 2. Returning 2
f(3) is 3 * 2 which equals 6. Returning 6
f(4) is 4 * 6 which equals 24. Returning 24
4! = 24
我怎么会得到。
f(1) is 1 * 1 which equals 1. Returning
f(2) is 2 * 1 which equals 2. Returning 2
f(3) is 3 * 2 which equals 6. Returning 6
f(4) is 4 * 6 which equals 24. Returning 24
在我的方法中打印
这是我的方法
public static int factorial(int num) {
if (num == 0) {
System.out.println("In f(" + num + ") and computing f(" + num
+ "). Returning " + 1);
return 1;
} else {
System.out.println("In f(" + num + ") and calling f(" + (num - 1)
+ ") . . .");
return num * factorial(num - 1);
}
打印出来
4! is . . .
In f(4) and calling f(3) . . .
In f(3) and calling f(2) . . .
In f(2) and calling f(1) . . .
In f(1) and calling f(0) . . .
In f(0) and computing f(0). Returning 1
4! = 24
答案 0 :(得分:1)
这样的事情可以解决问题:
public static int factorial(int num) {
if (num == 0) {
System.out.println("In f(0) and computing f(0). Returning 1");
return 1;
}
System.out.printf("In f(%d) and calling f(%d) . . .%n", num,
num - 1); // #1
int factorial = factorial(num - 1);
int result = num * factorial;
System.out.printf(
"f(%1$d) is %1$d * %2$d which equals %3$d. Returning %3$d%n",
num, factorial, result); // #2
return result;
}
In f(4) and calling f(3) . . . In f(3) and calling f(2) . . . In f(2) and calling f(1) . . . In f(1) and calling f(0) . . . In f(0) and computing f(0). Returning 1 f(1) is 1 * 1 which equals 1. Returning 1 f(2) is 2 * 1 which equals 2. Returning 2 f(3) is 3 * 2 which equals 6. Returning 6 f(4) is 4 * 6 which equals 24. Returning 24 24
注意factorial
递归调用是如何夹在两个print语句之间的(我们通过将它存储在一个新变量中而不是在内联中使用它的结果来实现这一点)。因此,所有第一个打印语句(#1
)都在第二个打印语句(#2
)之前执行,从而产生所需的格式。
此外,在这种情况下,printf
更有意义,使事情更容易阅读/开发。
答案 1 :(得分:0)
你正在直接回来,而不是让自己做出你要求的额外日志声明。您需要做的是设置一个等于返回的变量,然后您可以打印出“返回”语句,然后您就可以返回。
答案 2 :(得分:0)
取出你的“factorial(num - 1);”从return语句调用并将其保存在临时变量中。
e.x。
int retVal = factorial(num-1)
System.out.println("I'm about to return "+retVal);
return retVal;
答案 3 :(得分:0)
public static int factorial(int num)
{
int ret =0;
if (num == 0)
{
System.out.println("In f(" + num + ") and computing f(" + num+ "). Returning " + 1);
ret = 1;
}
else
{
System.out.println("In f(" + num + ") and calling f(" + (num - 1)+ ") . . .");
int fact = factorial(num - 1);
System.out.println("f("+num+") is "+num + " * "+fact + " which equals "+ num*fact+". Returning "+num*fact );
ret = num*fact;
}
return ret;
}