杭电acm 1001题,sum problem 总结网上的各种方法和注意事项,及其该题的注意事项!

Problem Description

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
 
-------------------------------------------------------------------------------------------------------------------------------
 题意:
  输入一个数字,输出从1到该数字所有数字的和。
 
该题的注意事项:避免变量的溢出。所以在所有acm中尽量减小数的位数。(注意:对于产生的小数,注意小数陷阱。因为有些小数不能精确表示。这里不赘述)。
 
避免方法1:(暴力破解法)
      略。
      解析:该方法直接避免了数据溢出,不做解说。但是,作为acm的解法,则失去了算法的趣味。算法,应该更加依赖数学表达式,思维等等,而不是语法。
避免方法2:
      这是我的代码:
#include <stdio.h>
int main(){
 int n;
 scanf("%d", &n);
 if (n % 2 == 0){
  printf("%d", (n / 2)*(n + 1));
 }
 else{
  printf("%d", (n + 1) / 2 * n);
 }
}
解析:该题目没有多大难度。但是存在运算过程中想不到的溢出。而结果也不存在溢出的情况。但是在过程中存在溢出的情况。从而造成结果的偏差。在过程中n*(n+1)会出现溢出。为了避免溢出。我做了上面的工作——除2。这样就可以解决了。
对该方法的优化:
#include<stdio.h>
int main()
{
int n,sum;
while(scanf("%d",&n)!=EOF)
{
sum=n/2.0*(n+1);
printf("%d ",sum);
}
return 0;
}
注意:这个优化方法简化了不用判断n是否为偶数或者奇数。但是存在一个问题。这种优化的方法,应用比较狭隘(浮点运算陷阱)。奇数产生了0.5在浮点型中能精确表示。
总结:注意在整个编程中确保每一个数是否出现溢出。
 
该内容是总结网上博客的结果的前提下添加了自己的观点。
欢迎大神吐槽。
原文地址:https://www.cnblogs.com/damaoranran/p/8423810.html