hdu1000 A + B Problem

it2022-05-05  182

A + B Problem

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 376937    Accepted Submission(s): 119082

Problem Description Calculate A + B.   Input Each line will contain two integers A and B. Process to end of file.   Output For each case, output A + B in one line.   Sample Input 1 1   Sample Output 2   大多数OJ的第一问,没发过博客,就拿这题练习了。。。。。 题目大意就不用说了。就是熟悉OJ的环境。。。 简单说一下OJ的输入。cin scanf() 等都是有返回值的。 为测试其返回值,编写了如下程序: #include<iostream> #include<cstdio> #include<windows.h> using namespace std; int main() { int x,a,b; freopen("cin.txt","r",stdin); int T=7; while(T--) { cout<<(cin>>a)<<endl; system("pause"); } }

其中cin.txt如下:1 2 3 4 5

在codeblock下的运行结果:

把程序改成如下:

#include<iostream> #include<cstdio> #include<windows.h> using namespace std; int main() { int x,a,b; freopen("cin.txt","r",stdin); int T=3; while(T--) { cout<<(scanf("%d",&a))<<endl; cout<<(scanf("%d%d",&a,&b))<<endl; system("pause"); } }

cin.txt文件不变,结果如下

可见cin的返回值可能是其地址或神马的,当无输入时,返回0;

而scanf返回的是成功读到的变量的数量

OJ的C++输入: while(cin>>a>>b)

这样当结束时,无输入,所以cin>>a>>b的返回值为0,结束循环。

用C可以这样:

while(~scanf("%d%d",&a,&b))

这样,当结束是返回值为-1,取~后为0;

也可以

while(scanf("%d%d",&a,&b)!=EOF)

因为EOF=-1;

当然根据上述内容,scanf可以灵活运用。

言归正传,还是给出Hdu1000这道报到题AC的代码,算是作为开门第一篇的结束:

#include<iostream> using namespace std; int main() { int a,b; while(cin>>a>>b) cout<<a+b<<endl; }

 

转载于:https://www.cnblogs.com/shumabaobei/p/hdu_1000.html


最新回复(0)