HDU 1001题解
|
Sum ProblemTime Limit: 1000/500 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 523855 Accepted Submission(s): 132962
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
|
题目链接:点击打开链接
这题虽然是道水题,但是粗心的人还是很容易出现
WA的,需要注意的有几点:
1.题目中要求输出格式中每个答案后面有一个空白行(followed by a blank line)
2.数据存储中int型的数据只能存储32位,如果超出,则会
WA
。(用推理公式解决问题时会出现,但是直接用for循环处理问题则不会出现这个问题)
针对问题2的解决方案有几种,比如先用double存储结果,最后在输出时类型转换为int型的;或者直接用int存储结果,但是计算公式中需要考虑当数字过大时,是否会超出内存。
C++的AC代码(推理公式)
#include <iostream>
using namespace std;
int main()
{
double n;
while (cin >> n)
cout << (int)(n*(n + 1) / 2) << endl << endl;
return 0;
}