1153: sum

题目描述

Hey, welcome toPDSU OJPingdingshan University Online Judge). In this problem, your task is to calculate SUM(n) = 1 + 2 + 3 + ... + n.

输入

The input will consist of a series of integers n, and n>=0,end of file EOF,one integer per line.

输出

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. 

样例输入

1
100

样例输出

1

5050

提示

来源

付高磊

这一题实际上非常简单的,不要多想。

用公式法和循环累加均能做出来。

方法一:使用循环累加法。

#include<stdio.h>
int main()
{
    int n,s,i;
    while(scanf("%d",&n)!=EOF)
    {
        s=0;
        for(i=1;i<=n;i++)
       {
           s+=i;
       }
       printf("%d\n\n",s);
    }
    return 0;
}

方法二:使用公式法,使用此方法时要考虑到n*(1+n)不能溢出,因为n是小于32位的数,所以可以把变量定义成long long 类型。

#include<stdio.h>
int main()
{
    long long n;
    while(scanf("%lld",&n)!=EOF)
    {
       printf("%lld\n\n",n*(1+n)/2);
    }
    return 0;
}


注:int型,占4个字节,32位
long int型,占4个字节,32位
long long int 类型,占8个字节,64位

以下是测试代码:

#include<stdio.h>
int main()
{
    int a;
    long b;
    long long c;
    printf("a为int型,占%d个字节\nb为long int型,占%d个字节\nc为long long int 类型,占%d个字节",sizeof(a),sizeof(b),sizeof(c));
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

COCO56(徐可可)

建议微信红包:xucoco56

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值