2011-09-02 42 views
0

我有以下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循環。 在此先感謝

+0

只是一個匆匆,你分配一個值之前做你的COUTS,這是可能的值是您的for循環的最後itteration中改變。將cout移到你的分配之後並查看那個輸出。 –

回答

4

它不應該是:

for(int i = 0; i < arr_size; i++) 

請注意,您修改maxsofar在最後循環迭代你已經印刷完畢,這就是爲什麼你看到一個區別 - 你可能添加在一個垃圾值上最後一次迭代,因爲你的離由一個循環界限。

希望你在享受編程珍珠

+0

是的,他爲數組之外的項目做了另一次迭代,這是垃圾。 – CMircea

2

for(int i = 0;i <= arr_size; i++) 

應該

for(int i = 0; i < arr_size; i++) 
       ^^^ 

你超越束縛的陣列。

1
for(int i = 0;i <= arr_size; i++) { 

當然不應該是<?大小通常意味着0到size-1是該數組的有效索引。

for(int i = 0;i < arr_size; i++) { 

這可能會導致您覆蓋您的數組並寫入另一個堆棧變量。

0

您的循環中溢出您的數組大小。 for循環應該是:

for(int i = 0;i < arr_size; i++) 

注意,在你的代碼中<=及以上<之間的差異。做適當的改變,你不會溢出你的數組。 :)

1

假設arr_size實際上是數組的大小,您的<=運算符導致您運行一個結束,addind垃圾到總和。

1

由於環路約束:

for(int i = 0;i <= arr_size; i++) 

你正在做一個額外的步驟,所以你看這是陣列以外的指數,併爲此具有一定的隨機值。

它應該是:

for(int i = 0;i < arr_size; i++) 
1

這是因爲您已經閱讀垃圾數組邊界之外:

for(int i = 0;i <= arr_size; i++) { // should be i < arr_size 
0
i <= arr_size 

應該

i < arr_size 
0

您打印出maxsofar在你的循環的頂部,所以你是n在迭代之後捕獲它的價值。值在循環內部被改變,而不在其外部。

這對您的情況尤其有害,因爲正如其他人指出的那樣,您最後一次迭代會經過數組的末尾,從而爲您的計數器添加無意義值。

慣用的方式,通過數組迭代是:

for (int i = 0; i < length; ++i) 
{ 
    // do Stuff 
} 
+0

哎唷!這真是愚蠢的我。在提出問題之前,應該先看看我的代碼。對不起,夥計..並感謝您的幫助 – ppaul74