请教一个基本的问题
用C语言编写一个程序,求前 n 项之和S值,其中 n≥1 ,x ≠ 0 。(n由键盘输入):S=1/2x-2x/3+3/5x-5x/8+8/13x-13x/21…
请问这个咋整呀?
double foo( unsigned n, double x ) { double result = 0; for( unsigned i=0,a=1,b=2; i!=n; ++i,b=b+a,a=b-a ) { if( i%2 == 0 ) result += a/(b*x); else result -= (a*x)/b; } return result; } #include <stdio.h> #include <assert.h> int main( void ) { assert( foo(1,1) == 1/2. ); assert( foo(2,1) == 1/2. - 2/3. ); assert( foo(3,1) == 1/2. - 2/3. + 3/5. ); assert( foo(1,0.5) == 1/(2*0.5) ); assert( foo(2,0.5) == 1/(2*0.5) - (2*0.5)/3 ); assert( foo(3,0.5) == 1/(2*0.5) - (2*0.5)/3 + 3/(5*0.5) ); }