该程序从用户那里获取一个正整数并计算该数字的阶乘。假设,然后用户输入 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()
函数。