一道计算e^n的函数题,我不知道哪里错了!!!求赐教
原理为:e^n=1+n+n^2/(2!)+n^3/(3!)+……+n^x/(x!)源代码如下:(x控制精度,n为指数)
#include
unsigned f1(unsigned p,unsigned q);
unsigned f2(unsigned r);
long double f3(unsigned n,unsigned x);
void main()
{
unsigned n,x;
printf("Please input n and x:");
scanf("%u%u",&n,&x);
printf("e^%u = %lf\n",n,f3(n,x));
}
unsigned f1(unsigned p,unsigned q) //计算n^x
{
unsigned pow=1;
if(q>0)
for(;q>0;--q)
pow*=p;
else
pow=1;
return pow;
}
unsigned f2(unsigned r) //计算x!
{
unsigned fac;
if(r==0||r==1)
fac=1;
else
fac=r*f2(r-1);
return fac;
}
long double f3(unsigned n,unsigned x) //计算e^x
{
long double exp=0;
unsigned i;
for(i=0;i<=x;i++)
exp+=1.0*f1(n,i)/f2(i);
return exp;
}
检验时发现:输入3 22和输入3 12结果有蛮大差异,而由3 22算出来的结果和e^3相同!!
x是控制精度的,不知道哪里出错了!!