#A000. A+B Problem
A+B Problem
Description
求两个数字的和。
Input
输入数据包含多组,每组由两个数字 和 组成。数字绝对值不超过 。
Output
对每组输入,输出 的结果。
Samples
1 31
123 456
32
579
提示
本题与一般的 不一样,测试数据有很多组,但并不知道具体数量,需要一直读取直到无数据可读。
由于本系统A系列的题目全是多组数据,需要读取到文件结束,因此无比掌握以下方法:
C:scanf返回值为EOF时结束。
#include
int main() {
int a, b;
while (scanf("%d%d", &a, &b) != EOF) printf("%d\n", a + b);
return 0;
}
C++:cin读取失败时结束。
#include
using namespace std;
int main() {
int a, b;
while (cin >> a >> b) cout << a + b << '\n';
return 0;
}
Java:Scanner用hasNext方法返回为false时结束。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
int a = sc.nextInt(), b = sc.nextInt();
System.out.println(a + b);
}
}
}
Python:请在try内读取,直到抛出异常。
while True:
try:
a, b = map(int, input().split())
print(a + b)
except:
break
本系统Java时限为2倍,Python时限为3倍。
Python的同学,如果你要直接使用读取的字符串(比如:不对字符串转换为int),务必先strip,否则字符串可能会带上回车符。
对于读取到文件结尾的读入方式,你可以通过以下方式来输入结束符:Ctrl+Z。