Skip to content

Latest commit

 

History

History
63 lines (43 loc) · 1.65 KB

File metadata and controls

63 lines (43 loc) · 1.65 KB

C 程序:使用递归查找数字的阶乘

原文: https://www.programiz.com/c-programming/examples/factorial-recursion

在此示例中,您将学习查找用户使用递归输入的非负整数的阶乘。

要理解此示例,您应该了解以下 C 编程主题:


正数n的阶乘由下式给出:

factorial of n (n!) = 1 * 2 * 3 * 4 *...  * n 

负数的阶乘不存在。0的阶乘为1

在此示例中,您将学习使用递归查找数字的阶乘。 访问此页面以了解如何使用循环查找数字的阶乘


使用递归的阶乘

#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
    int n;
    printf("Enter a positive integer: ");
    scanf("%d",&n);
    printf("Factorial of %d = %ld", n, multiplyNumbers(n));
    return 0;
}

long int multiplyNumbers(int n) {
    if (n>=1)
        return n*multiplyNumbers(n-1);
    else
        return 1;
} 

输出

Enter a positive integer: 6
Factorial of 6 = 720 

假设用户输入了 6。

最初,从main()调用multiplyNumbers(),并将 6 作为参数传递。

然后,将 5 从相同的函数传递给multiplyNumbers()(递归调用)。 在每个递归调用中,参数n的值减小 1。

n的值小于 1 时,没有递归调用,并且阶乘最终返回给main()函数。