-
描述
-
Your task is to find the sum of all integer numbers lying between 1 and N inclusive.
-
输入
-
There are multiple test cases.
The input consists of a single integer N that is not greater than 10000 by it's absolute value.
输出
- Write a single integer number that is the sum of all integer numbers lying between 1 and N inclusive. 样例输入
-
3
样例输出
-
6
来源
- ural
-
There are multiple test cases.
题意:
就是给一个整数 N 需要作出 1~N 之间的整数累加求和,如
N = 1 ans = 1;
N = 2 ans = 3;
N = 0 ans = 0;
N = -2 ans = -2;(1-1-2)
.................
思路:
看这个题目在 436 坑了不少 ACMer 昂,最近在学递归,直接上代码吧。
代码:
#include<stdio.h>
#include<math.h>
int SUM(int x) {//递归求解键入负数的处理
if(x==2)
return 2;
return x+SUM(x-1);
}
int main() {
int n,ans;
while(scanf("%d",&n)!=EOF) {
if(n>0)
ans=n*(n+1)/2;
else if(n==0)
ans=1;
else if(n==-1)
ans=0;
else if(n<=-2) {
n=n*(-1);//坑人用 abs()函数运行错误
ans=-SUM(n);
}
printf("%d\n",ans);
}
return 0;
}