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
#include <iostream>
#include <cstdio>
#include <cstring>
#include <climits>
#include <cstdlib>
using namespace std;
//const int MAXINT=int(((unsigned int)(~0))>>1);//求最大int值,也可用<limits.h>中的INT_MAX;
int main()
{
char s1[1000],s2[1000],c;
while(scanf("%s %c %s",s1,&c,s2)!=EOF)
{
printf("%s %c %s\n",s1,c,s2);//不小心忘了,WA了一次;
double a=atof(s1),b=atof(s2);//字符串转化为浮点型,头文件<stdlib.h>;如果此题字符串足够长的话,转化浮点就无能为力了;
if(a>INT_MAX)
printf("first number too big\n");
if(b>INT_MAX)
printf("second number too big\n");
if((c=='+'&&a+b>INT_MAX)||(c=='*'&&a*b>INT_MAX))
printf("result too big\n");
}
return 0;
}