栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

Given three integers A, B and C in (−263,263), 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.

题意

给出三个整数A,B,C,如果A+B>C,则输出true;否则,输出false

思路1

由于long long的范围是[-2^63,2^63),因此题目中给出的两个整数相加有可能会出现溢出(正溢出或负溢出)所谓溢出即两个正数之和等于负数或者两个负数之和等于正数,所以直接进行大小判断会造成错误。要分别处理两种溢出的情况

1.正溢出情况,当A+B>2^63 ,A + B > C 必然成立 但是A+B超出long long的正向最大值而溢出,由题目可知 A 和 B最大均为 2^63 - 1, 故A+B最大为2^64 - 2, 因此使用long long 存储正溢出后的区间为[-2^63, -2],即当A>0,B>0,A+B<0时输出true


2.负溢出情况,同理正溢出情况 使用long long 存负溢出后的区间为[0, 2^63),即当A<0,B<0,A+B>=0时输出false

3.没有溢出时正常输出

AC代码

#define _CRT_SECURE_NO_WARNINGS
#include 
using namespace std;

int main()
{
	int n;
	scanf("%d", &n);
	for (int i = 1; i <= n; i++)
	{
		long long int a, b, c;
		scanf("%lld%lld%lld", &a, &b, &c);//用cin最后一个测试点会错误
		long long res = a + b;  //必须先存放到long long 中再与c比较否则后两组数据会错误
		bool flag;
		if (a > 0 && b > 0 && res < 0)	flag = true;//正溢出为true
		else if (a < 0 && b < 0 && res >= 0)	flag = false;//负溢出为false
		else if (res > c)	flag = true;	//无溢出时 a + b > c 为true
		else if (res <= c)	flag = false;	//无溢出时 a + b <= c 为false
		if (flag == true)
			cout << "Case #" << i << ": true" << endl;
		else if(flag == false)
			cout << "Case #" << i << ": false" << endl;
	}
	return 0;
}

思路2 使用long doule可以精确到20位

AC代码

#include 
using namespace std;

int main()
{
	int n;
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		long double a, b, c;//long doubel能精确到20位
		cin >> a >> b >> c;
		if (a + b > c)
			cout << "Case #" << i << ": true" << endl;
		else 
			cout << "Case #" << i << ": false" << endl;
	}
	return 0;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/722799.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号