怎么用c语言编写1+2-3+4-5......+100的程序来啊

2024-12-23 05:18:43
推荐回答(5个)
回答1:

#include
void main()
{
int i;
int sum=1;
for(i=2; i<=100; i++)
{
if (i%2==0)//偶数相加
{
sum=sum+i;
}
else//奇数
{
sum=sum-i;
}
}
printf("sum is %d", sum);
}

回答2:

#include
int main()
{
int i=2;
int sum=1;
//方法一:
for (i=2 ; i<=100 ; i++)
(i%2==0)?sum+=i:sum+=-1*i;

/*
//方法二:
do
{
(i%2==0)?sum+=i:sum+=-1*i;
i++;
} while (i<=100);
*/
/* //方法三:
while (i<=100)
{
(i%2==0)?sum+=i:sum+=-1*i;
i++;
}
*/
printf("%d\n",sum);
return 0;
}

回答3:

#include
void main()
{
int sum,number;
clrscr();
for(number=1;number<=100;number++)
{
sum=sum+number;
}
printf("1+2-3+4-5......+100的和为%d",sum);
}

回答4:

int resul=0;
for(int i=1;i<=100;i++)
{
if(i&0x01)
result=result+i;
else
result=result-i;
}

回答5:

//---------------------------------------------------------------------------

#include
int sum(int n)
{
int s;
if (n>1) {
s=n%2?-n:n;
s+=sum(n-1);
}
else s=n;
return s;
}
int main(void)
{
printf("%d",sum(100));
return 0;
}
//---------------------------------------------------------------------------