△UVA465

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,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('')才结束转换,并将结果返回。字符串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
",a,c,b);
14         m=atof(a);
15         n=atof(b);
16         if(m>MAX)
17             printf("first number too big
");
18         if(n>MAX)
19             printf("second number too big
");
20         if(c=='+' && (m+n) > MAX)
21             printf("result too big
");
22         if(c=='*' && (m*n) > MAX)
23             printf("result too big
");
24     }
25     return 0;
26 }




原文地址:https://www.cnblogs.com/youdiankun/p/3687485.html