/*输入一个正整数n,计算1-(2/3)+(3/5)-(4/7)+(5/9)-...的前n项和*/
#include<stdio.h> int main(void) { int i,n,numerator,denominator,flag; /*numerator是分子,denominnator是分母,flag是常数系数*/
double sum,item; /*sum是总和,item是各项的值*/
printf("Enter n:"); scanf("%d",&n); numerator=1; denominator=1; sum=0; flag=1;
/*循环n次求解各项并相加求和*/ for(i=1;i<=n;i++){ item=flag*(numerator*1.0/denominator); numerator=numerator+1; denominator=denominator+2; flag=-flag; sum=sum+item; } printf("sum=%lf ",sum); return 0; }