要实现用户输入一个数,并计算1-2+3-4+...+n的和,我写的代码是
#include <stdio.h>
int main()
{
int n = 0;
while (n <= 0) {
printf("请输入一个正整数:\n");
scanf("%d", &n);
}
int sum = 0;
int number= 0;
while (number< n) {
number++;
if (number% 2 == 1) {
sum += number; //奇数
} else {
sum -= number;
}
}
printf("%d\n", sum);
return 0;
} |
|