本文共 1318 字,大约阅读时间需要 4 分钟。
杭电刷题第二篇
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~n的和,输入只要求输入n而已,别搞错了。
方法一: 直接使用一个for循环进行累加从1~n:#includeint main(){ int sum=0,n; while(scanf("%d",&n)!=EOF){ for(int i=1;i<=n;i++) { sum+=i; } printf("%d\n",sum); printf("\n"); sum=0; } return 0;}
方法二:
利用等差数列求和,在这里有一个容易出错的地方,因为题目要求“the result will be in the range of 32-bit signed integer”所以在使用等差数列公式时候如果先乘再除,会造成数据溢出的问题,所以要先除再乘。但是如果先除的话,注意区分当n是偶数和非偶数的情况,否则除运算不正确。所以正确的代码如下:#includeint main(){ int sum=0,n; while(scanf("%d",&n)!=EOF){ if(n%2==0) sum=n/2*(n+1); else sum=(n+1)/2*n; printf("%d\n\n",sum); sum=0; } return 0;}
错误代码如下:
#includeint main(){ int sum=0,n; while(scanf("%d",&n)!=EOF){ sum=n*(n+1)/2; printf("%d\n\n",sum); sum=0; } return 0;}
还有一个经常错误的地方就是结果的输出“For each case, output SUM(n) in one line, followed by a blank line”,他的意思是输出结果后空一行。
转载地址:http://yxrdb.baihongyu.com/