题意:处理两个大整数,判断有哪些数超出了int的取值范围
注意事项:
①使用istringstream()需要调用#include <sstream>函数
用法:istringstream对象可以绑定一行字符串,然后以空格为分隔符把该行分隔开来。
②int最大值为0x7fffffff,两个ff组成一个字节,恰好为四个字节
#include <iostream>
#include <string>
#include <sstream>//使用istringstream()需要调入的头文件
using namespace std;
string getMaxStr()
{
int n=0x7fffffff;
string s="";
while(n!=0)
{
s=(char)(n%10+'0')+s;
n=n/10;
}
return s;
}
bool cmp(const string &a,const string &b)
{
int alen=a.size();
int blen=b.size();
if(alen==blen)
{
for(int i=0;i<alen;i++)
if(a[i]!=b[i])
return a[i]>b[i];
}
else
{
return alen>blen;
}
return false;
}
int main()
{
string a,op,b;
string max_str=getMaxStr();
while(cin>>a>>op>>b)
{
bool over=false;
cout<<a<<" "<<op<<" "<<b<<endl;
while(a.size()>1 && a[0]=='0')//###,wa n多次,大整数问题记着清除前置零,判断为‘0’而不是0.
a.erase(0,1);
while(b.size()>1 && b[0]=='0')
b.erase(0,1);
if(cmp(a,max_str))
{
cout<<"first number too big"<<endl;
over=true;
}
if(cmp(b,max_str))
{
cout<<"second number too big"<<endl;
over=true;
}
if(over)
{
if(op=="+")
cout<<"result too big"<<endl;
else if(op=="*" && a!="0" && b!="0")
cout<<"result too big"<<endl;
}
else
{
long long aa,bb,cc;
istringstream(a)>>aa;
istringstream(b)>>bb;
if(op=="+")
cc=aa+bb;
else if(op=="*")
cc=aa*bb;
if(cc>0x7fffffff)
cout<<"result too big"<<endl;
}
}
return 0;
}