HZNUOJ

Input-Output Lecture (0) for ACM Freshman

Tags:     萌新入坑题    先做这道题,小白们  基本输入输出
Time Limit:  1 s      Memory Limit:   1024 MB
Submission:4500     AC:2921     Score:10.00

Description

给出两个整数a和b,计算a+b的值。

Input

输入有多组,每组占一行,包含两个整数a和b (-100<=a,b<=100) 。

Output

对于每组输入,输出一行,即a+b的值。

Samples

input
1 5 10 20
output
6 30
input
1 2
output
3

Hint

这是一道四处可见的A+B练习题。
此处输入有多组,因此我们需要写一个循环来执行多次的a+b操作。但由于题目并未告诉你具体有多少组 输入,所以还需要在代码中判断当前的输入是否为最后一组。在C语言中,scanf若读取到末尾则返回EOF (实际值为-1),在C++中,cin读取到末尾返回0。
因此我们可以写出如下代码:

C版:

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

C++版:

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

Java版:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNextInt()) {
            int a = in.nextInt();
            int b = in.nextInt();
            System.out.println(a + b);
        }
    }
}

Pascal(FPC):

program p1000(Input,Output); 
var 
    a,b:Integer; 
begin 
    while not eof(Input) do 
    begin 
        Readln(a,b); 
        Writeln(a+b); 
    end; 
end.

Python2/3版:

import sys
for line in sys.stdin:
    a = line.split()
    print(int(a[0]) + int(a[1])) 

PHP版:

<?php
while (fscanf(STDIN, "%d%d", $a, $b) == 2) {
    print ($a + $b) . "\n";
}
?>

C#版:

using System;
using System.Linq;
 
namespace ConsoleApp
{
    public class Program
    {
        private static void Main()
        {
            string line;
            while((line = Console.ReadLine()) != null)
            {
                Console.WriteLine(line.Split().Select(int.Parse).Sum());
            }
        }
    }
}

Lua版:

local count = 0
function string.split(str, delimiter)
    if str==nil or str=='' or delimiter==nil then
        return nil
    end
   
    local result = {}
    for match in (str..delimiter):gmatch("(.-)"..delimiter) do
        table.insert(result, match)
    end
    return result
end
while true do
    local line = io.read()
    if line == nil or line == "" then break end
    local tb = string.split(line, " ")
    local sum = 0
    for i=1, #tb do
        local a = tonumber(tb[i])
        sum = sum+a
    end
    if count>0 then
        io.write("\n")
    end
    io.write(string.format("%d", sum))
    count = count+1
end

Perl版:

my $input;
while($input = <>){
    chomp($input);
    my @array = split ' ',$input;
    print $array[0]+$array[1],"\n";
}

GO版:

package main
import "fmt"
import "io"
 
func main() {
	var A, B int
	for {
        _, err := fmt.Scan(&A, &B)
        if err == io.EOF {
            break
        }
        fmt.Println(A+B)
    }
}

Author

CHEN, Yupeng