C++ 对于2个功能实现中的1个,代码为整数溢出
我正在解决 我有两种解决这个问题的方法,我相信它们是等价的。然而,我得到了错误C++ 对于2个功能实现中的1个,代码为整数溢出,c++,overflow,integer-overflow,C++,Overflow,Integer Overflow,我正在解决 我有两种解决这个问题的方法,我相信它们是等价的。然而,我得到了错误 第24行:Char 52:运行时错误:有符号整数溢出:-944784000*4不能在类型“int”(solution.cpp)中表示。对于某些大输入的第一个代码,但对于第二个输入,我没有表示。我认为这两个代码之间没有任何功能上的区别,那么为什么第一个代码会溢出呢 代码1 int最大乘积(向量和nums){ if(nums.empty())返回0; 自动n=nums.size(); int min_num=nums[0
第24行:Char 52:运行时错误:有符号整数溢出:-944784000*4不能在类型“int”(solution.cpp)中表示。
对于某些大输入的第一个代码,但对于第二个输入,我没有表示。我认为这两个代码之间没有任何功能上的区别,那么为什么第一个代码会溢出呢
代码1
int最大乘积(向量和nums){
if(nums.empty())返回0;
自动n=nums.size();
int min_num=nums[0];
int max_num=nums[0];
int curr_max=nums[0];
对于(int i=1;i
代码2
int最大乘积(向量和nums){
if(nums.empty())返回0;
自动n=nums.size();
int min_num=nums[0];
int max_num=nums[0];
int curr_max=nums[0];
对于(int i=1;i
这两段代码并不相等
if(nums[i] < 0) {
max_num = std::max(nums[i], min_num*nums[i]);
min_num = std::min(nums[i], max_num*nums[i]); // This uses modified max_num.
}
if(nums[i]<0){
max_num=std::max(nums[i],min_num*nums[i]);
min_num=std::min(nums[i],max_num*nums[i]);//这使用修改后的max_num。
}
我相当肯定这是一个错误。如果你把它改成
if(nums[i] < 0) {
auto temp = std::max(nums[i], min_num*nums[i]);
min_num = std::min(nums[i], max_num*nums[i]); // This uses unmodified max_num
max_num = temp;
}
if(nums[i]<0){
自动温度=std::max(nums[i],min_num*nums[i]);
min_num=std::min(nums[i],max_num*nums[i]);//这使用未修改的max_num
最大值=温度;
}
那么它们将是等价的
if(nums[i] < 0) {
max_num = std::max(nums[i], min_num*nums[i]);
min_num = std::min(nums[i], max_num*nums[i]); // This uses modified max_num.
}
if(nums[i] < 0) {
auto temp = std::max(nums[i], min_num*nums[i]);
min_num = std::min(nums[i], max_num*nums[i]); // This uses unmodified max_num
max_num = temp;
}