常见的递归算法当属阶乘了,如求5!,此处需要特别注意溢出问题。算法实现如下:
#include <iostream>
using namespace std;
#define U64 unsigned long long
#define U16 unsigned short
U64 factorial(U64 n)
{
if(1 == n)
return 1;
else
{
return n*factorial(n-1);
}
}
int main()
{
U64 result=0;
U64 n=0;
cout<<"***** 递归算法 *****"<<endl;
cout<<" 请输入待求的阶乘数:";
cin>>n;
if(n>64)
{
cout<<"请输入小于64的数"<<endl;
return -1;
}
result = factorial(n);
cout<<endl;
cout<<"计算结果:" <<endl;
cout<<n<<"的阶乘为:"<<result<<endl;
return 0;
}
Juyin@2018/4/25