C++For循环.Int.值的求和不正确

C++ For Loop. Int. values are not being summed correctly

本文关键字:求和 不正确 循环 Int C++For      更新时间:2023-10-16

这里是初学者。所以我试图让这个代码打印出每年的总价值。我为每个值输入了10,第三年它会返回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;
}

您没有初始化数组

int total[3];

因此,在本声明中,

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

行为是未定义的。

写入

int total[3] = {};

此外,此声明在外循环内

int yr_total = 0;

是多余的。未使用变量。

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

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

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

理想情况下,应该初始化总数组,而不是将其保留为垃圾值。

int total[3] = {};

希望能有所帮助。