用递归计算???

来源:百度知道 编辑:UC知道 时间:2024/05/26 05:04:46
px(x,n)=x-x^2+x^3-x^4+...(-1)^(n-1)*x^n
用递归实现

基本思想:
px(x,n)=(-1)^(n-1)*x^n+px(x,n-1)
所以有这样的递归代码形式:
double px(x,n){
if(x==1)
return x;
else return (-1)^(n-1)*x^n+px(x,n-1);
}
至于x^n如何实现,不同的语言有不同的数学函数可以实现。
在c语言下有:
#include <math.h>
double px(int x,int n)
{
if(n==1)
return x;
else return pow(-1,n-1)*pow(x,n)+px(x,n-1);
}
void main()//测试下
{ int x=4,n=2;
double d=px(x,n);
printf("%f\n",d);

}

double px(int x,int n)
{
static double s=0,c=1 ;
double u;
int y=n%2?1:-1;
if (n>1) px(x,n-1);
c*=x;
s+=y*c;
return s ;

}