我有以下C++函數,即試圖尋找最大子陣列總和,負和正整數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值更改爲135205,外面的for循環。 在此先感謝
只是一個匆匆,你分配一個值之前做你的COUTS,這是可能的值是您的for循環的最後itteration中改變。將cout移到你的分配之後並查看那個輸出。 –