原文: https://www.programiz.com/cpp-programming/examples/factorial-recursion
使用递归查找非负整数(由用户输入)的阶乘的示例。
要理解此示例,您应该了解以下 C++ 编程主题:
该程序从用户处获取一个正整数,然后计算该数字的阶乘。 假设用户输入 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);elsereturn 1;}
输出
Enter an positive integer: 6Factorial 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()函数。
