ACM 输出输入入门

以 hdu acm steps为例讲解


例1

http://acm.hdu.edu.cn/game/entry/problem/show.php?chapterid=1&sectionid=1&problemid=3001


题意大概就是要你求 a+b,很简单,第一次写大概可以写到

#include <iostream>
using namespace std;

int main()
{
    int a,b;
    cin>>a>>b;
    cout<<a+b<<endl;
    return 0;
}

可是Sample Input 跟 Sample Output是什么意思呢。

Sample Input 就是黑框里你打上去的内容

Sample Output就是黑框里正确的程序显示的内容。

一般把黑框分成两部分,input就是键盘打进去的数据输入,output就是程序运行完的数据输出


观察例题的样例输入,发现题目的要求是,输入可以有不限定的行数,每一行输入会有一个输出,所以可以这样写

#include <iostream>
using namespace std;

int main()
{
    int a,b;
    while(cin>>a>>b)
    {
        cout<<a+b<<endl;
    }
    return 0;
}

//下面是scanf printf 代替cin cout 版
int main()
{
    int a,b;
    while(scanf("%d%d",&a,&b)!=EOF)
    {
        cout<<a+b<<endl;
    }
    return 0;
}

cin输入成功会返回一个非0数,使得程序继续,直到没数据输入,cin返回0,while循环退出

scanf输入成功会返回输入成功的变量的数目,否则返回EOF


例2

http://acm.hdu.edu.cn/game/entry/problem/show.php?chapterid=1&sectionid=1&problemid=3002

#include <iostream>
using namespace std;

int main()
{
    int alltest,a,b;
    while(alltest>0)
    {
        cin>>a>>b
        cout<<a+b<<endl;
        alltest--;
    }
    return 0;
}

//下面是精简版
int main()
{
    int alltest,a,b;
    while(alltest--)
    {
        cin>>a>>b
        cout<<a+b<<endl;
    }
    return 0;
}

例3

http://acm.hdu.edu.cn/game/entry/problem/show.php?chapterid=1&sectionid=1&problemid=3003

#include <iostream>
using namespace std;

int main()
{
    int a,b;
    while(cin>>a>>b && a!=0 && b!=0)
    {
        cout<<a+b<<endl;
    }
    return 0;
}

//下面是scanf printf 代替cin cout 版
int main()
{
    int a,b;
    while(scanf("%d%d",&a,&b)!=EOF && a!=0 && b!=0)
    {
        cout<<a+b<<endl;
    }
    return 0;
}

例4

http://acm.hdu.edu.cn/game/entry/problem/show.php?chapterid=1&sectionid=1&problemid=3003

#include <iostream>
using namespace std;

int main()
{
    int n,x,sum;
    while(cin>>n && n!=0)
    {
        sum=0;
        for(int i=0;i<n;i++)
        {
            cin>>x;
            sum=sum+x;
        }
        cout<<sum<<endl;
    }
    return 0;
}

例5

http://acm.hdu.edu.cn/game/entry/problem/show.php?chapterid=1&sectionid=1&problemid=3007

#include <iostream>
using namespace std;

int main()
{
    int a,b;
    bool isTheFirstTest=true;
    while(cin>>a>>b)
    {
        if(isTheFirstTest==true) //第一个test不额外输入多一个空行
        {
            isTheFirstTest=false;
        }else{
            cout<<endl;         //不是第一个test的都额外输出多一个空行
        }
        cout<<a+b<<endl;
    }
    return 0;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值