编写程序1-3+5-7+9-11+13……前20项的和
#include <stdio.h> int main() { int i; int j=1; int count=0; int sum=0; for(i=1;i<100;i+=2) { sum+=i*j; j*=-1; count++; if(count==20) break; } printf("1-3+5-7……前20项的和为:%d\n",sum); return 0; }
#include<stdio.h>
int main()
{
int i,j,sum1,sum2,sum;
for(i=1,sum1=0;i<20;i=i+2)
sum1+=i;
for(j=-2,sum2=0;j>-21;j=j-2)
sum2+=j;
sum=sum1+sum2;
printf("1-2+3-…-20=%d\n",sum);
return 0;
}
类似的改成+4和-4
#include<stdio.h>
int main()
{
int i,j,sum1,sum2,sum;
for(i=1,sum1=0;i<100;i=i+2)
sum1=sum1+i;
for(j=-2,sum2=0;j>-101;j=j-2)
sum2=sum2+j;
sum=sum1+sum2;
printf("1-2+3-…-100=%d",sum);
return 0;
}