南阳理工:sum of all integer numbers

来源:互联网 发布:淘宝联盟手机可以提现 编辑:程序博客网 时间:2024/05/22 11:56

sum of all integer numbers

时间限制:1000 ms  |  内存限制:65535 KB
难度:0
描述
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
注意:一定要看清楚题,是1——N之间的数求和,N可能为负值。另外,由于N的绝对值有限定,所以可以直接用公式计算而不会溢出,否则要分情况讨论做,先用偶数部分除以二在求和。
#include<stdio.h>
int main()
{
   int n;
   while(scanf("%d",&n)!=EOF)//由于开始不小心误写成了NULL,所以一直超时,所以写代码时一定要小心啊!
   {
         if(n>0) printf("%d\n",(n+1)*n/2);     
          else printf("%d\n",1-n*(n-1)/2);
              
    }
  return 0;
}

 
 
原创粉丝点击