初學者在這裏。所以我試圖讓這個代碼打印每年的總價值。我已經爲每個值輸入了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;
}
有趣。我錯誤地認爲,如果我聲明數組,我可以使用for循環將值添加到它。但是我猜想在它初始化之前你不能這麼做。謝謝! – Sabazios
@Sabazios根本沒有。你不受歡迎:) –
@Sabazios:你可以爲它增加價值,但你不知道它原來的「價值」是什麼,所以你也不知道你的結果會是什麼。雖然技術上整個事情都有UB,所以...... –