此程序从用户那里获取一个正整数,并计算该数字的阶乘。假设用户输入 6,则:
Factorial will be equal to 1*2*3*4*5*6 = 720
在此示例中,您将学习如何使用递归函数查找数字的阶乘。
访问此页面了解如何使用循环计算阶乘。
示例:使用递归计算阶乘
#include<iostream>
using namespace std;
int factorial(int n);
int main() {
int n;
cout << "Enter a positive integer: ";
cin >> n;
cout << "Factorial of " << n << " = " << factorial(n);
return 0;
}
int factorial(int n) {
if(n > 1)
return n * factorial(n - 1);
else
return 1;
}
输出
Enter an positive integer: 6 Factorial of 6 = 720
在上面的程序中,假设用户输入数字 6。该数字被传递给 factorial()
函数。
在此函数中,6 乘以 (6 - 1 = 5) 的阶乘。为此,数字 5 再次被传递给 factorial()
函数。
同样,在下一个迭代中,5 乘以 (5 - 1 = 4) 的阶乘。并且,4 被传递给 factorial()
函数。
这将一直持续到值达到 1,然后函数返回 1。
现在,每个函数都将返回值以计算 1 * 2 * 3 * 4 * 5 * 6 = 720
,该值被返回到 main()
函数。
注意:此程序不适用于大于 12 的数字。这是因为这些数字的阶乘非常大,超出了 int
类型可以存储的值的范围。
您可以将 unsigned long
用作 factorial()
函数的返回类型,但这仍然不足以获取大多数数字的阶乘。
另请阅读