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
大数处理题目,就是要你判断给出的表达式第一个数字、第二个数字、第三个数字是否溢出
很多人会想到写字符串相加、相乘函数,但我的想法是double的最大范围既然是1e308,为什么不用double处理呢
但是用double处理还是有很多问题,比如要把字符串转化为double就很麻烦
看了别人的代码学了sscanf()的用法,发现简直可以和Java的各种集合类parse方法相媲美了
字符串处理神器!!!
我还有一个想法是既然输入的数都是非负整数,那么如果输入数中有一个越界,结果肯定也会越界,但是这样写错误了,我怀疑是*0的情况没有考虑到!
#include <map> #include <cmath> #include <vector> #include <string> #include <cstdio> #include <cstring> #include <cstdlib> #include <iostream> #include <algorithm> #define esp 1e-9 #define MAXN 10010 #define ll long long #define BUG system("pause") #define SW(a,b) a^=b;b^=a;a^=b; using namespace std; double INF = 0x7fffffff; int main(void){ char opand1[MAXN]; char opand2[MAXN]; char operat; while(scanf("%s %c %s", opand1, &operat, opand2)!=EOF){ // cout << "LONG LONG_MAX = " << pow(2,63)-1 << endl; // cout << "INF = " << INF << endl; printf("%s %c %s\n", opand1, operat, opand2); double aa, bb; int flag = 0; sscanf(opand1, "%lf", &aa); sscanf(opand2, "%lf", &bb); // cout << "aa = " << aa << endl; // cout << "bb = " << bb << endl; if(aa > INF){ cout << "first number too big" << endl; } if(bb > INF){ cout << "second number too big" << endl; } if(operat=='+' && aa+bb>INF){ cout << "result too big" << endl; } else if(operat=='*' && aa*bb>INF){ cout << "result too big" << endl; } } return 0; }