题目描述
Hey, welcome toPDSU OJPingdingshan University Online Judge). In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + ... + n.
输入
The input will consist of a series of integers n, and n>=0,end of file EOF,one integer per line.
输出
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.
样例输入
1
100
样例输出
1
5050
提示
来源
这一题实际上非常简单的,不要多想。
用公式法和循环累加均能做出来。
方法一:使用循环累加法。
#include<stdio.h>
int main()
{
int n,s,i;
while(scanf("%d",&n)!=EOF)
{
s=0;
for(i=1;i<=n;i++)
{
s+=i;
}
printf("%d\n\n",s);
}
return 0;
}
方法二:使用公式法,使用此方法时要考虑到n*(1+n)不能溢出,因为n是小于32位的数,所以可以把变量定义成long long 类型。
#include<stdio.h>
int main()
{
long long n;
while(scanf("%lld",&n)!=EOF)
{
printf("%lld\n\n",n*(1+n)/2);
}
return 0;
}
注:int型,占4个字节,32位
long int型,占4个字节,32位
long long int 类型,占8个字节,64位
以下是测试代码:
#include<stdio.h>
int main()
{
int a;
long b;
long long c;
printf("a为int型,占%d个字节\nb为long int型,占%d个字节\nc为long long int 类型,占%d个字节",sizeof(a),sizeof(b),sizeof(c));
return 0;
}