acm编程连加的问题
来源:百度知道 编辑:UC知道 时间:2024/06/27 17:23:19
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
我的程序如下,但总是提示“答案错误”。
#include<stdio.h>
void main()
{
int i,n=1,sum;
while(scanf("%d", &n) != EOF)
{
sum=n*(n+1)/2;
printf("%d\n\n",sum);
return 0;
}
}
1楼和2楼的还是不行,提示“答案错误”
我是在这里做的,是作业……
http://acm.hdu.edu.cn
#include<stdio.h>
void main()
{
int i,n=1,sum;
while(scanf("%d", &n) != EOF)
{
sum=n
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
我的程序如下,但总是提示“答案错误”。
#include<stdio.h>
void main()
{
int i,n=1,sum;
while(scanf("%d", &n) != EOF)
{
sum=n*(n+1)/2;
printf("%d\n\n",sum);
return 0;
}
}
1楼和2楼的还是不行,提示“答案错误”
我是在这里做的,是作业……
http://acm.hdu.edu.cn
#include<stdio.h>
void main()
{
int i,n=1,sum;
while(scanf("%d", &n) != EOF)
{
sum=n
好了,经过N次WA,我知道了.
如下,之前WA的原因,他的n太大了,先算n*(n+1)时,便溢出了,
所以我们改变一下顺序,先除以2,然后再乘另一个数,便不会溢出了.
#include<stdio.h>
int main() {
int n,sum;
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);
}
return 0;
}
将return 从括号搞出来,就不断连续进行多次运算 ,你的题目从哪里来的,比较有意思- -||
主函数是没有返回值的,你却写了个return 0;
将return 从括号搞出来,就不断连续进行多次运算
#include<stdio.h>
void main()
{
int i,n=1,sum;
while(scanf("%d", &n) != EOF)
{
sum=n*(n+1)/2;
printf("%d\n\n",sum);
}
return ;
}