判断乘法溢出

来源:百度知道 编辑:UC知道 时间:2024/05/30 20:50:36
给Integer重载安全的乘法运算符 在溢出时提示

另 下面的加法有无错误???

Integer Integer::operator+(Integer &in)

{ int temp = 0;

if(value/2+in.value/2>=1073741824||value/2+in.value/2<=-1073741824)

{ cout<<endl<<"<operator + >Warning : Data Overflow!"<<endl;

return *this;

}

else

{ temp = value + in.value;

if(value>0 == in.value>0)

{ if(a>0 == temp>0)

{ return Integer(temp);

}

else

{ cout<<endl<<"<operator + >Warning : Data Overflow!"<<endl;

return *this;

}

else return Integer(temp);

}

}

}
我需要的是乘法的... 还有检查下加法有没有错误....

你这分明是加法。。

if(a>0 == temp>0) 这个a是哪来的?

上面不是已经判断了它不会溢出了么, 下面的判断应该是多余的

总的来说我觉得这样判断更快点:

int temp = value + in.value;
if ( (in.value>0) == (temp > value))
{
return Integer(temp);
} else
{
cout << "Overflow" << endl;
return *this;
}

如果你只是想检查32位int型的乘法溢出, 那其实很简单, 结果放在long long 里面,很容易看到溢出了没有。 比如这样:
Integer& Integer::operator *(Integer &a)
{
union {
long long ll;
long l[2];
} temp;
temp.ll = (long long)value * a.value;
if (temp.l[1] == 0 || temp.l[1] == -1) return Integer(temp.l[0]);
else {
cout << "Overflow" << endl;
}
}