#include<stdio.h> int main(void) { int denominator,flag,i,n; double item,sum; printf("Enter n:"); scanf("%d",&n); flag=1; denominator=1; sum=0; for(i=1;i<=n;i++){ item=flag*1.0/denominator; sum=sum+item; flag=-flag; denominator=denominator+2; } printf("sum=%f ",sum); return 0; }
/*计算1+2+3+...+n*/ #include<stdio.h> int main(void) { int i,n,sum; printf("Enter n:"); scanf("%d",&n); sum=0; for(i=1;i<=n;i++){ sum=sum+i; } /*输出累加和*/ printf("Sum of numbers from 1 to %d is %d ",n,sum); return 0; }