C ++ For Loop。诠释。值未正确汇总

时间:2015-11-03 22:54:14

标签: c++

初学者。所以我试图让这段代码打印出每年的总价值。我为每个价值输入10,而第3年它返回126而我预计为120.其他两年返回正确值120.我无法弄清楚为什么这不起作用意图。

#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;
}

3 个答案:

答案 0 :(得分:6)

您没有初始化数组

int total[3];

因此在本声明中

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

行为未定义。

int total[3] = {};

外部循环内的这个声明

int yr_total = 0;

是多余的。该变量未被使用。

答案 1 :(得分:1)

C ++不会将变量初始化为已知值。在这种情况下,您将年度总计汇总为一组未初始化的数据(total)。令人惊讶的是,第1年和第2年没有表现出类似的问题。

您似乎尝试使用变量yr_total而不是数组总计来清除此数据。尝试使用以下内容替换年份循环的第一行:total[year] = 0;

答案 2 :(得分:1)

您的代码的主要问题是初始化部分。

理想情况下,您应该初始化整个数组,而不是留下垃圾值。

int total[3] = {};

希望它有所帮助。

相关问题