调试因子递归

时间:2012-08-14 01:03:56

标签: c recursion

我是C编程语言的新手,我正在尝试学习递归来计算给定数字的阶乘。我的问题是,如果我输入'5',则调试printf语句正在打印2,6,24,120。如果用相应的值替换函数调用并一次计算阶乘,它如何打印4次?

#include<stdio.h>
#include<stdlib.h>

int factorial(int n);

int main()
{
        int num;
        int fact_val;
        printf("Enter the number for which you are going to compute the factorial:");
        scanf("%d",&num);

        fact_val=factorial(num);

        printf("The factorial of the given number is %d\n",fact_val);

        return 0;
}

int factorial(int n)
{
        int factorial_val;
        if(n==1)
        return 1;
        else
        {
                factorial_val=factorial(n-1)*n;
                printf("Debugger-%d\n",factorial_val);
        }
        return factorial_val;
}

1 个答案:

答案 0 :(得分:4)

当您达到基本情况时,立即return而不是打印。

因此,您会看到printf的情况:5,4,3,2,当函数传递1时,不会打印该值:而是return

此外,您在打印之前递归,因此案例按顺序打印,至少先打印:第一次打印只在您一直递归到 2 。因此,您会看到:2,6,24,120。只有当您从当前递归返回时,才会打印中间值。

记下递归以使其更清晰:

5 -> recurse with 4:
    4 -> recurse with 3:
        3 -> recurse with 2:
            2 -> recurse with 1:
                1 -> base case, just return...
            printf (1 * 2) = 2;
        printf (2 * 3) = 6;
    printf (6 * 4) = 24;
printf (24 * 5) = 120;