PATA 1065.A+B and C (64bit) (20)解题报告

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

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&gtC, 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
作者: HOU, Qiming
单位: PAT联盟
时间限制: 100ms
内存限制: 64MB
代码长度限制: 16KB

AC代码:

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
	int t;
	cin>>t;
	long long a,b,c,result;
	bool flag;
	int times=1;
	while(t--)
	{
		cin>>a>>b>>c;
		result=a+b;
		if(a>0&&b>0&&result<0)
		flag=true;
		else if(a<0&&b<0&&result>=0)
		flag=false;
		else if(result>c)
		flag=true;
		else
		flag=false;
		if(flag==true)
		printf("Case #%d: true\n",times++);
		else
		printf("Case #%d: false\n",times++);
	}
	return 0;
}

总结:本题考察的是计算机组成原理中,浮点数加减法,正负溢出的知识,实际解题过程中我们根据浮点数不同的溢出情况构造了不同的输出分支

1.当A+B>2^63,显然,A+B>C是成立的,但发生了正溢出(因为long long 的范围是[-2^63,2^63]),A+B的最大值可能是2^64-2,那么按照正溢出的定义,会溢出到[-2^63,-2],于是我们就可以这么判定:当A>0,B>0,且A+b<0时为正溢出,输出true;

2.同上,当A+B<-2^63,A+B<C是显然的,A+B因为小于 long long 的负向最小值而发生了负溢出,A+B最小为-2^64,所以负溢出的区间是[-2^63,0]。所以我们在A<0,B<0,A+B<=0的情况下,可以认为发生负溢出,输出false

3.当不发生溢出时,就直接进行判定

ps:C语言有一个头文件叫做<limits.h>,里面对整型数据的数据类型的表达值范围有了定义,例如LLong_MAX就定义了long long 变量的最大值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值