2015-11-03 21 views
2

初學者在這裏。所以我試圖讓這個代碼打印每年的總價值。我已經爲每個值輸入了10,第3年它返回126,而我期望120.另外兩年返回正確的值120.我無法弄清楚爲什麼這不能按預期工作。C++ For Loop。詮釋。值未被正確彙總

#include <iostream> 
int main() 
{ 
    using namespace std; 
    const int Years = 3; 
    const int Months = 12; 
    int booksales[Years][Months]; 
    int total[3]; 
    for (int year = 0; year < Years; ++year) 
    { 
     int yr_total = 0; 
     for (int month = 0; month < Months; ++month) 
     { 
      cout << "Enter book sales for year " << (year + 1) 
      << " month " << (month + 1) << ": "; 
      cin >> booksales[year][month]; 
      total[year] += booksales[year][month]; 
     } 
    } 
cout << "TOTAL for year 1: " << total[0] << endl; 
cout << "TOTAL for year 2: " << total[1] << endl; 
cout << "TOTAL for year 3: " << total[2] << endl; 
cout << "OVERALL TOTAL: " << total[0] + total[1] + total[2] << endl; 
return 0; 
} 

回答

6

你沒有在此聲明

total[year] += booksales[year][month]; 

的行爲是不確定的初始化數組

int total[3]; 

這樣。

int total[3] = {}; 

同樣在此聲明外環

int yr_total = 0; 

是多餘的內部。該變量未被使用。

+0

有趣。我錯誤地認爲,如果我聲明數組,我可以使用for循環將值添加到它。但是我猜想在它初始化之前你不能這麼做。謝謝! – Sabazios

+0

@Sabazios根本沒有。你不受歡迎:) –

+0

@Sabazios:你可以爲它增加價值,但你不知道它原來的「價值」是什麼,所以你也不知道你的結果會是什麼。雖然技術上整個事情都有UB,所以...... –

1

C++不會將變量初始化爲已知值。在這種情況下,您正在將您的年度總計加總爲未初始化數據的數組(total)。令人驚訝的是,第1年和第2年並未出現類似的問題。

它看起來像你試圖清除這個數據與變量yr_total而不是數組總數。嘗試用以下代碼替換年份循環的第一行:total[year] = 0;

1

代碼的主要問題是初始化部分。

理想情況下,您應該初始化總數組而不是將其與垃圾值一起保留。

int total[3] = {}; 

希望它有幫助。