465 - Overflow

来源:互联网 发布:python输入ctrl c 编辑:程序博客网 时间:2024/06/02 04:19
Overflow 

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

Input

An unspecified number of lines. Each line will contain aninteger, one of the two operators + or *, andanother integer.

Output

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

Sample Input

300 + 39999999999999999999999 + 11

Sample Output

300 + 39999999999999999999999 + 11first number too bigresult 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不会导致溢出。数组num1和num2的大小的确定就与double有关。这里还用到了函数atof()包含在stdlib.h头文件中,能够很方便地将字符数字转化成double型数据。

题中的数据要与int比较大小, int的范围是-2^31~2^31-1,也就是-2147483648~2147483647,因为题目要求是正整数,所以取MAX_INT2147483647


 
这里还有一点要注意的:用scanf输入时,格式控制符之间要有一个空格,不能紧挨着



如果你不是采用这种方法,那就得注意以下两点:


(1)    如果用到函数atoi(),数据可能会溢出,提交时会显示“Runtime Error”。小心……


(2)    测试数据应该考虑前导零的情况。如:00000234657453 + 000454332315你应该把前导零忽略。


 


 


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

 

代码:

#include<stdio.h>
#include<stdlib.h>
#define max 2147483647
char x[301],y[301];
int main()
{
 double a,b;
 char ch;
 while(scanf("%s %c%s",x,&ch,y)==3)
 {
  printf("%s %c%s\n",x,ch,y);
  a=atof(x);
  b=atof(y);
  if(a>max)printf("firstnumber too big\n");
  if(b>max)printf("secondnumber too big\n");
  if(ch=='+'&& a+b>max)printf("result too big\n");
  if(ch=='*'&& a*b>max)printf("result too big\n");
 }
    return0;
}

 


 
 
原创粉丝点击