1

我写了一个阶乘程序。我已经完成了整个程序,它运行没有任何问题。但是,我希望输出看起来像这样

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
4

4 回答 4

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;
}
在 f(4) 并调用 f(3) 。. .
在 f(3) 并调用 f(2) 。. .
在 f(2) 并调用 f(1) 。. .
在 f(1) 并调用 f(0) 。. .
在 f(0) 和计算 f(0) 中。返回 1
f(1) 是 1 * 1,等于 1。返回 1
f(2) 是 2 * 1 等于 2。返回 2
f(3) 是 3 * 2 等于 6。返回 6
f(4) 是 4 * 6 等于 24。返回 24
24

请注意factorial递归调用是如何夹在两个打印语句之间的(我们通过将其存储在一个新变量中而不是使用其结果内联来做到这一点)。结果,所有第一个打印语句 ( #1) 在任何第二个打印语句 ( ) 之前执行#2,从而产生所需的格式。

此外,在这种情况下,printf更有意义,并且使事情更容易阅读/开发。

于 2013-04-23T21:54:25.720 回答
0

您直接返回,而不是让自己做出您要求的额外日志声明。您需要做的是设置一个等于返回值的变量,然后您可以打印出您的“Returning”语句,然后您可以返回。

于 2013-04-23T21:47:27.537 回答
0

拿出你的“阶乘(num - 1);” 从 return 语句调用并将其保存在临时变量中。

前任

int retVal = factorial(num-1)
System.out.println("I'm about to return "+retVal);
return retVal;
于 2013-04-23T21:49:41.377 回答
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;
}
于 2013-04-23T22:09:06.670 回答