正数
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、
最初,
multiplyNumbers()
是从
main()
调用的,6 作为参数传递。
然后,从同一个函数(递归调用)将 5 传递给
multiplyNumbers()
。在每次递归调用中,参数
n 的值减 1、
当
n 的值小于1 时,没有递归调用,阶乘最终返回给
main()
函数。