以 hdu acm steps为例讲解
例1
http://acm.hdu.edu.cn/game/entry/problem/show.php?chapterid=1§ionid=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§ionid=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§ionid=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§ionid=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§ionid=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;
}