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
注意字符串的前导零,输出是要有,但是计算式要忽略,自己编的程序一直A不掉,看到网上的程序短的吓一跳
#include<stdio.h>
#include<stdlib.h>
#define max 2147483647
int main()
{
char s1[10001],s2[10001],c;
double x,y;
while(scanf("%s %c %s",s1,&c,s2)!=EOF)
{
printf("%s %c %s\n",s1,c,s2);
x=atof(s1);
y=atof(s2);
if(x>max)printf("first number too big\n");
if(y>max)printf("second number too big\n");
if(c=='+'&&x+y>max)printf("result too big\n");
if(c=='*'&&x*y>max)printf("result too big\n");
}
return 0;
}
double类型有15-16位的精度,足够表示,自己的程序也贴一下,求大神指点
#include<iostream>
#include<sstream>
#include<cstdio>
#include<string>
using namespace std;
#define MAX 0xffffffff>>1
bool StrToL(string str, long long &ans){
stringstream s;
for(int i = 0; i < str.size(); i++){
if(str[i] == '0')
str.erase(i, 1);
else
break;
}
if(str.size() > 10)
return false;
s << str;
s >> ans;
if(ans > MAX)
return false;
return true;
}
int main(void){
string str1, str2, oper;
long long x, y, ans;
#ifndef ONLINE_JUDGE
freopen("f:\\infile.txt", "r", stdin);
#endif
while(cin >> str1 >> oper >> str2){
x = 0;
y = 0;
cout << str1 << " " << oper << " " << str2 << endl;
if(!StrToL(str1, x))
cout << "first number too big" << endl;
if(!StrToL(str2, y))
cout << "second number too big" << endl;
if((!StrToL(str1, x) || !StrToL(str2, y))){
if(oper == "+"){
cout << "result too big" << endl;
continue;
}
else{
if((str1 != "0") && (str2 != "0")){
cout << "result too big" << endl;
continue;
}
}
}
if(oper == "+")
ans = x + y;
else
ans = x * y;
if(ans > MAX)
cout << "result too big" << endl;
}
return 0;
}