Loading

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;
} 
posted @ 2021-10-28 22:24  August_丶  阅读(31)  评论(0编辑  收藏  举报