C++ Box类特定测试用例异常:溢出与比较逻辑错误排查
C++ Box类Bug排查与修复
问题现象
编写的Box类代码在运行指定测试用例时,出现两个异常:
- 体积计算结果为负数(预期值
33004122803,实际得到-1355615565) - 一次体积比较结果错误(预期输出
Lesser,实际输出Greater)
代码实现
#include<bits/stdc++.h> using namespace std; class Box{ private: int l,b,h; public: Box(){ l=0; b=0; h=0; } Box(int a,int d,int c){ l=a; b=d; h=c; } Box(Box& source){ l=source.l; b=source.b; h=source.h; } int getLength(){ return l; } int getBreadth (){ return b; } int getHeight (){ return h; }; long long CalculateVolume(){ return this->l*this->b*this->h; }; friend bool operator<(Box & s1,Box &source){ return (s1.l*s1.b*s1.h)<(source.l*source.b*source.h); } friend ostream& operator<<(ostream& out,const Box& B){ out<<B.l<<" "<<B.b<<" "<<B.h; return out ; } }; void check2() { int n; cin>>n; Box temp; for(int i=0;i<n;i++) { int type; cin>>type; if(type ==1) { cout<<temp<<endl; } if(type == 2) { int l,b,h; cin>>l>>b>>h; Box NewBox(l,b,h); temp=NewBox; cout<<temp<<endl; } if(type==3) { int l,b,h; cin>>l>>b>>h; Box NewBox(l,b,h); if(NewBox<temp) { cout<<"Lesser\n"; } else { cout<<"Greater\n"; } } if(type==4) { cout<<temp.CalculateVolume()<<endl; } if(type==5) { Box NewBox(temp); cout<<NewBox<<endl; } } } int main() { check2(); }
测试用例
6 2 1039 3749 8473 4 3 1456 3836 283 3 729 3749 272 2 4839 283 273 4
Bug原因分析与修复
1. 体积计算负数问题
l、b、h都是int类型,三个int相乘时,运算结果会先以int类型存储。测试用例中1039*3749*8473的结果远超过32位int的最大值(2^31-1=2147483647),导致整数溢出,溢出后的数值变成负数,之后再转换为long long返回,所以得到错误的负数结果。
2. 比较结果错误问题
operator<中同样是先计算三个int的乘积,乘积溢出后变成负数,此时比较的是溢出后的错误值,而非真实的体积大小,导致比较结果反转。
修复方案
在计算乘积前,先将其中一个操作数转换为long long,强制整个乘法运算以long long类型进行,避免溢出:
- 修改
CalculateVolume函数:
long long CalculateVolume(){ return (long long)this->l * this->b * this->h; };
- 修改
operator<函数:
friend bool operator<(Box & s1,Box &source){ return (long long)s1.l * s1.b * s1.h < (long long)source.l * source.b * source.h; }
这样计算时会先将l转换为long long,后续的乘法都会以64位整数进行,不会出现溢出,能得到正确的体积值和比较结果。
内容的提问来源于stack exchange,提问作者Sudhanshu Kumar
相关产品推荐
相关产品推荐

