A+B問題是一個基礎的程式設計問題。通常是資訊學線上解題系統用來測試提交和輸入輸出方法的題目。[1]

一般描述 編輯

輸入兩個數  (一般是在整數範圍內),輸出 的計算結果。

範例程式碼 編輯

Java 編輯

import java.util.*;
public class AB {
	public static void main(String[] args) {
		Scanner sc=new Scanner(System.in);
		int a,b;
		a=sc.nextInt();
		b=sc.nextInt();
		System.out.println(a+b);
	} //main end
} //AB end

C語言 編輯

#include <stdio.h>

int main(void)
{
    int a, b;
    scanf("%d %d", &a, &b);
    printf("%d\n", a + b);
    return 0;
}

C++ 編輯

#include <iostream>

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

#include <iostream>

using namespace std;

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

Pascal 編輯

var a,b:longint;
begin
    readln(a,b);
    writeln(a+b)
end.

Ruby 編輯

gets.strip.split.map(&:to_i).reduce(:+)

Python 編輯

適用於 Python 3 :

print(sum(map(int, input().split())))

Fortran 編輯

PROGRAM P1000
		IMPLICIT NONE
		INTEGER :: A, B
		READ(*,*) A, B
		WRITE(*, "(I0)") A + B
	END PROGRAM P1000

PHP 編輯

<?php
$input = trim(file_get_contents("php://stdin"));
list($a, $b) = explode(' ', $input);
echo $a + $b;

擴充 編輯

有的版本會對命題的條件進行調整,增加或刪除某些限制條件,使得以上範例代碼無法通過測試,例如:

  1. 在有的版本的A+B問題中,雖然輸入的A和B都在整數的範圍之內,但A+B的值可能會超出這個範圍。這時候就要使用數值範圍更廣的資料類型,或者使用高精度計算
  2. 有的版本需要使用十進位以外的進位制,或者需要使用字母表示。
  3. 有的問題需要使用特殊的輸入輸出方法(例如檔案輸入),也可能要求提交的時候加入一些附加資訊,需要仔細閱讀測評網站的說明文件要求才能正確通過測試。

參考文獻 編輯

  1. ^ 北京大學線上解題系統「POJ」中的A+B Problem頁面存檔備份,存於網際網路檔案館

參見 編輯