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:使用
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:直接使用
long double
儲存a,b,c值long double
精讀更高,且可表示的範圍更大,直接計算(a+b)和c的大小,並輸出結果即可!
-
參考:
-
[PAT 1065 A+B and C大數運算][溢位]
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;
}