我想写一个递归函数来计算sin(x)的Maclaurin扩展。它是这样的:
sin(x)=x-(xˆ3/3!)+(xˆ5/5!)-(xˆ7/7!)+(xˆ9/9!)
...
double sin(int n, double x){ // n is the exponent, x is the value
if(n == 1)
return x;
if() // WHAT TO SET THE CONDITION TO ?
return sin(n-2,x) - (pow(x,n-2)/fact(n-2)); // fact is a function I have to calculate the factorial
else
return sin(n-2,x) + (pow(x,n-2)/fact(n-2));
}
我在设置if条件时遇到问题,所以有一次我添加值,下次我减去值。
答案 0 :(得分:1)
double sin(int n, double x){ // n is the exponent, x is the value
if(n == 1)
return x;
if( ((n-1)/2) % 2 != 0)
return sin(n-2,x) - (pow(x,n)/fact(n)) ;
else
return sin(n-2,x) + (pow(x,n)/fact(n)) ;
}