您的位置:首页 > 其它

杭电OJ--1001

2016-11-05 16:03 218 查看

Sum Problem

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.

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

Code:

#include <iostream>

using namespace std;

int main()
{
int n;
while(cin>>n)
{
int sum=0;
for(int i=1;i<=n;++i)
{
sum=sum+i;
}
cout<<sum<<endl;
cout<<endl;
}
return 0;
}


Tip:

  本题较为简单,但是需要注意在计算sum时不可以使用sum=n*(n+1) /2,因为当n逐渐变大时n*(n+1)/2未发生溢出,但是此时n*(n+1)已经发生溢出,但是由于程序会先进行n*(n+1)运算,因此会导致程序出错 。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  杭电 1001 Sum-Proble