1. 程式人生 > 其它 >1065 A+B and C (64bit) (20 分)

1065 A+B and C (64bit) (20 分)

1. 題目

Given three integers A, B and C in \((−2^{63},2^{63})\), you are supposed to tell whether A+B>C.

Input Specification:

The first line of the input gives the positive number of test cases, T (≤10). Then T test cases follow, each consists of a single line containing three integers A, B and C, separated by single spaces.

Output Specification:

For each test case, output in one line Case #X: true if A+B>C, or Case #X: false otherwise, where X is the case number (starting from 1).

Sample Input:

3
1 2 3
2 3 4
9223372036854775807 -9223372036854775808 0

Sample Output:

Case #1: false
Case #2: true
Case #3: false

Thanks to Jiwen Lin for amending the test data.

2. 題意

輸入a和b,判斷a+b是否大於c。

3. 思路——簡單模擬

  1. 方法1:使用long long儲存a,b,c值

    • 這裡需要使用scanf讀入資料,如果使用cin讀入,最後一個測試點過不了!原因:如果讀取的數溢位,cin得到的是最大值,而scanf得到的是溢位後的值,測試資料如果有 [2^63 -1 2^63-2],這樣用cin就會得到錯誤結果了。(參考:1065. A+B and C (64bit) (20)-PAT甲級真題下Aliencxl的評論!)

    • 這裡因為long long的取值範圍為[-e^63, e^63),所以a,b兩數相加時可能會出現溢位的情況,兩個正數之和等於負數或兩個負數之和等於整數,那麼就是溢位了。

      • a>0,b>0時,如果兩數相加可能導致溢位,因為a和b的最大值為\(2^{63}-1\),所以a+b的範圍理應為\((0,2^{64}-2]\),而溢位得到的結果應該為\([-2^{63},-2]\)

        即a>0,b>0,a+b<0時為正溢位,輸出true。

      • a<0,b<0時,如果兩數相加也可能導致溢位,因為a和b的最小值為\(-2^{63}\),所以a+b的範圍理應為\([-2^{64},0)\),而溢位得到的結果應該為\([0,2^{63})\)

        即a<0,b<0,a+b≥0時為負溢位,輸出false

  2. 方法2:直接使用long double儲存a,b,c值

    • long double精讀更高,且可表示的範圍更大,直接計算(a+b)和c的大小,並輸出結果即可!
  3. 參考:

    1. 1065 A+B and C (64bit)

    2. 1065. A+B and C (64bit) (20)-PAT甲級真題

    3. [PAT 1065 A+B and C大數運算][溢位]

    4. int型別整數的表示範圍

4. 程式碼

方法1:

#include <iostream>
#include <string>

using namespace std;

typedef long long LL;

int main()
{
	LL n;
	LL a, b, c;
	cin >> n;
	for (int i = 1; i <= n; ++i)
	{
		scanf("%lld%lld%lld", &a, &b, &c);
		if (a > 0 && b > 0 && a + b < 0)
			cout << "Case #" << i << ": true" << endl;
		else if (a < 0 && b < 0 && a + b >= 0) 
			cout << "Case #" << i << ": false" << endl;
		else if (a + b > c)
			cout << "Case #" << i << ": true" << endl;
		else cout << "Case #" << i << ": false" << endl;
	}
	return 0;
} 

方法2:

#include <iostream>

using namespace std;

typedef long long LL;s
typedef long double LD;

int main()
{
	LL n;
	LD a, b, c;
	cin >> n;
	for (int i = 1; i <= n; ++i)
	{
		cin >> a >> b >> c;
		if (a + b > c)
			cout << "Case #" << i << ": true" << endl;
		else 
			cout << "Case #" << i << ": false" << endl;
	}
	return 0;
}