Time Limit: 1000/500 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Problem Description
Hey, welcome to HDOJ(Hangzhou Dianzi University Online Judge).
In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + ... + n.
In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + ... + n.
Input
The input will consist of a series of integers n, one integer per line.
Output
For each case, output SUM(n) in one line, followed by a blank line. You may assume the result will be in the range of 32-bit signed integer.
Sample Input
1
100
Sample Output
1
5050
Author
DOOM III
正确解
#include <stdio.h>
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int i;
int sum=0;
for(i=1;i<=n;i++)
sum+=i;
printf("%d\n\n",sum);
}
return 0;
}
注
一、题目求1+2+3+......+n的值
二、输出结果后要有空白行
错误解
#include <stdio.h>
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
printf("%d\n\n",n*(n+1)/2);
return 0;
}
错误原因
因为求和公式我们最后会除以2,题目中指明了result是在32位范围内,但并不代表在除以2之前,也就是运行到(n*(n+1))这里,值还是在范围里面