△UVA465 - Overflow(判断大数相加相乘是否会溢出)

Overflow 

Write a program that reads an expression consisting of two non-negative integer and an operator. Determine if either integer or the result of the expression is too large to be represented as a ``normal'' signed integer (type integer if you are working Pascal, type int if you are working in C).

 

Input

An unspecified number of lines. Each line will contain an integer, one of the two operators + or *, and another integer.

 

Output

For each line of input, print the input followed by 0-3 lines containing as many of these three messages as are appropriate: ``first number too big'', ``second number too big'', ``result too big''.

 

Sample Input

 

300 + 3
9999999999999999999999 + 11

 

Sample Output

 

300 + 3
9999999999999999999999 + 11
first number too big
result too big

借鉴的别人的。

题目大意:判断大数相加相乘是否会溢出。

这道题体现了浮点数的优势。不用字符串的相关操作,怎么实现两个大数的乘积、和?  int肯定不行,范围太小;long long的范围(-2^63~2^63-1,比-10^19~10^19略小)虽说比int大了许多,但还是有点小;double的范围是:-1.7*10^(-308) ~ 1.7*10^308 ,这范围看起来足够大了,那就试试吧!结果证明:用double不会导致溢出。

即使用64位整数(注意long long要I64d输出),溢出也会变成负数,判断起来比较困难。浮点数可以用指数表示。例如,double的正值取值范围为 4.94065645841246544E-324 到 1.79769313486231570E+308。意思是可以将上300位字符串形式转换成双精度浮点数,最多会丢失精度而已。知道这个性质后,用双精度浮点数来解决这道题就异常简单了。

函数atof() stdlib.h头文件中,能够很方便地将字符数字转化成double型数据。 可以忽略掉前导零。

函数说明 atof()会扫描字符串s,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('\0')才结束转换,并将结果返回。字符串s可包含正负号、小数点或E(e)来表示指数部分,如123.456或123e-2。

 1 #include<cstdio>
 2 #include<stdlib.h>
 3 
 4 #define maxn 1005
 5 #define MAX 0x7fffffff
 6 
 7 int main()
 8 {
 9     char a[maxn],b[maxn],c;
10     double m,n;
11     while(scanf("%s %c %s",a,&c,b) != EOF)
12     {
13         printf("%s %c %s\n",a,c,b);
14         m=atof(a);
15         n=atof(b);
16         if(m>MAX)
17             printf("first number too big\n");
18         if(n>MAX)
19             printf("second number too big\n");
20         if(c=='+' && (m+n) > MAX)
21             printf("result too big\n");
22         if(c=='*' && (m*n) > MAX)
23             printf("result too big\n");
24     }
25     return 0;
26 }
 
 

 



转载于:https://www.cnblogs.com/youdiankun/p/3687485.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值