【发布时间】:2011-09-02 18:24:03
【问题描述】:
我有以下 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。 提前致谢
【问题讨论】:
-
只是匆匆忙忙,您在分配值之前正在执行 couts,在 for 循环的最后一次迭代期间值可能会发生变化。将 couts 移到分配后并查看该输出。