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
我的答案:
改之前:
include<stdio.h>
void main()
{
while(1)
{
long int n,sum=0;
scanf("%d",&n);
while(n)
{
sum+=n;
n-=1;
}
printf("%d\n",sum);
}
}
这里主要的问题是
Time Limit Exceeded。原因嘛就出在了我的循环语句while上。
改之后:
include<stdio.h>
void main()
{
long int n,sum=0;
while(scanf("%d",&n)!=EOF)
{
while(n)
{
sum+=n;
n-=1;
}
printf("%d\n\n",sum);
sum=0;
}
}
改过之后,原while中的内容换成了while(scanf("%d",&n)!=EOF)。一些题目需要测试n次,就会用到这条语句。
此外此题还有一个坑,观察output的输出格式,1与100之间空了两行,故我们输出是也应该吧它体现出来。printf("%d\n\n",sum);(:(:(: