用C++求N的阶乘怎么做???

来源:百度知道 编辑:UC知道 时间:2024/05/30 19:19:25

完整程序如下,算法其实很简单,只是遍历n到1,然后这几个数相乘起来给s,程序里面加了一个判断,超出数据表达范围就输出over int area,然后返回0.
#include<iostream>
using namespace std;
int fac(int n)
{
int s=1;
for (int i=n;i>0;i--)
{
if (s<=s*i) s=s*i;
else
{
cout<<"over int area"<<endl;
return 0;
};
}
return s;
}
void main()
{

cout<<"10!="<<fac(10)<<endl;
cout<<"30!="<<fac(30)<<endl;//30的阶乘超过了int的表达范围,所以返回0,0表示不能表示结果.你可以试着用更大的整型.
}

在做递归的练习,看到阶乘,就写了个tail recursion: (最多能算到34的阶乘)
#include <iostream>
using namespace std;

unsigned long factorial (unsigned long number,unsigned long acc)
// acc is an accumulator to record the each computing n*(n-1)
// so acc shall be initialized as 1
{
if (number==0) return acc;
return factorial(number-1,number*acc);
}

in