//c++小程序:利用递归方法计算阶乘
//递归:在函数中调用函数自身的方法称为递归;递归应设置退出条件,否则会陷入死循环。
//下面是用递归方法(特点:代码简洁)计算阶乘的代码和注释:
#include<iostream>
#include<string>
using namespace std;
int k = 0; //记录递归函数被调用次数
long long Factorial(long long x) { //递归函数 Factorial,参数x:长整形,返回值为x!。
if (x == 1) { //递归函数退出条件
return 1;
}
else{
cout << "The factorial is called " << (++k) << " times;" << "x="<<x<<endl; //显示被调用次数
return x*Factorial(x - 1);//程序核心语句(即调用函数自身),只有参数值大于1时,才进行下一级的调用。
};
}
int main() {
long x;
cout << "Please input Num:";
cin >> x;
cout << "The result is " <<Factorial(x)<< "." << endl;
system("pause");
return 0;
}