- //2> 提示用户输入一个正整数n,计算1-2+3-4+5-6+…+n的和
- #include <stdio.h>
- int main()
- {
- int n = 0;
- while (n<=0)
- {
- printf("请输入一个正整数:\n");
- scanf("%d",&n );
- }
-
- int sum=0;
- int a=0;//默认被加的数值
- if (n%2==0)
- {
- while (a<n )
- {
- a = a+2;
- sum = sum -1;
- }
- }
-
-
- if (n%2==1)
- {
- while (a<n )
- {
- a = a+2;
- sum = sum +1;
- }
- }
-
- printf("%d\n",sum);
- return 0;
- }
复制代码 |
|