我有以下 C++ 函数,它试图在负整数和正整数数组中找到最大子数组和
int MaxSubArray::find_max_subarray(void) {
int maxsofar =0 ;
int maxendinghere = 0;
for(int i = 0;i <= arr_size; i++) {
cout << "maxending here is: " << maxendinghere << endl;
cout << "maxsofar is: " << maxsofar << endl;
maxendinghere += array[i];
maxendinghere = max(0,maxendinghere);
maxsofar = max(maxendinghere,maxsofar);
}
int retvalue = maxsofar;
cout << "Max so far final is" << maxsofar << endl;
cout << "Max ending here is " << maxendinghere << endl;
return retvalue;
}
对于包含 10,20,30,-50,50 的数组,我得到以下输出
maxending here is: 0
maxsofar is: 0
maxending here is: 10
maxsofar is: 10
maxending here is: 30
maxsofar is: 30
maxending here is: 60
maxsofar is: 60
maxending here is: 10
maxsofar is: 60
maxending here is: 60
maxsofar is: 60
Max so far final is135205
Max ending here is 135205
Max sub array is 135205
谁能告诉我为什么变量 maxsofar 在 for 循环之外将值更改为 135205。 提前致谢
最佳答案
不应该是:
for(int i = 0; i < arr_size; i++)
?
请注意,您在打印完 后的最后一个循环迭代中修改了 maxsofar
,这就是为什么您会看到差异的原因 - 您可能添加了垃圾由于你的逐一循环边界,最后一次迭代的值。
希望您喜欢Programming Pearls。
关于C++局部变量改变值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7287710/