杭电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:
1100
Sample Output:
15050
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)运算,因此会导致程序出错 。相关文章推荐
- 杭电OJ-1001
- 杭电OJ 1001
- 杭电oj 1001
- 杭电OJ 1001
- 【杭电 OJ】1001 Sum Problem
- 杭电OJ——第1000,1001题
- 杭电OJ_DIY_YTW2_1001 A Mathematical Curiosity
- 杭电OJ1001
- 杭电oj 1001
- 杭电oj1001题 a+b
- 杭电oj 1001 sum problem
- 杭电OJ编码1001
- 杭电oj~~1001
- 我的杭电oj之旅——1001
- 杭电oj 1001 记录一下
- 杭电oj-1001-Sum Problem
- Java解题-杭电OJ-1001题
- 杭电OJ 1001
- 杭电oj1001排序 交换次数
- 杭电OJ_DIY_YTW2_1001 A Mathematical Curiosity