我刚刚开始使用C++ Primer Plus,但遇到了一些麻烦。

const int MONTHS = 12;
const int YEARS = 3;
int sales[YEARS][MONTHS] = {0};
const string months[MONTHS] = {"January", "February", "March", "April", "May", "June", "July",
                               "August", "September", "October", "November", "December"
                              };

for (int year = 0; year < YEARS; year++)
{
    for (int month = 0; month < MONTHS; month++)
    {
        cout << "Please enter year " << year + 1 << " book sales for the month of " << months[month] << ": \t";
        cin >> sales[year][month];

    }
}

int yearlyTotal[YEARS][3] = {0};
int absoluteTotal = 0;

cout << "Yearly sales:" << endl;

for (int year = 0; year < YEARS; year++)
{
    cout << "Year " << year + 1 << ":";

    for (int month = 0; month < MONTHS; month++)
    {
        absoluteTotal = (yearlyTotal[year][year] += sales[year][month]);

    }

    cout << yearlyTotal[year][year] << endl;

}

cout << "The total number of books sold over a period of " << YEARS << " years is: " << absoluteTotal << endl;

我希望展示所有三年的总数。其余代码工作正常:输入正常,单个年度输出正常,但是我无法将三年的总和累加为一个最终总数。

示例数据将为每个选项输入1,总共给我三个12:



最终的12应该显然是36

我确实有一个总的工作量,但没有个别的总工量。我搞砸了,扭转了局面。

最佳答案

#include <iostream>
#include <string>
using namespace std;
int main (void)
{
const int MONTHS = 12;
const int YEARS = 3;
int sales[YEARS][MONTHS] = {0};
const string months[MONTHS] = {"January", "February", "March", "April", "May", "June", "July",
                               "August", "September", "October", "November", "December"
                              };

for (int year = 0; year < YEARS; year++)
{
    for (int month = 0; month < MONTHS; month++)
    {
        cout << "Please enter year " << year + 1 << " book sales for the month of " << months[month] << ": \t";
        cin >> sales[year][month];

    }
}

int yearlyTotal[YEARS] = {0};
int absoluteTotal = 0;

cout << "Yearly sales:" << endl;

for (int year = 0; year < YEARS; year++)
{
    cout << "Year " << year + 1 << ":";

    for (int month = 0; month < MONTHS; month++)
    {
        yearlyTotal[year] += sales[year][month];
    }
    absoluteTotal += yearlyTotal[year];

    cout << yearlyTotal[year] << endl;

}

cout << "The total number of books sold over a period of " << YEARS << " years is: " << absoluteTotal << endl;
return 0;
}
  • 您只需要在每月计数
  • 之外增加absoluteTotal
  • 您只需要一个一维数组即可计算年度计数。

  • 当涉及到这样的事情时,先将它们写在纸上是有帮助的。

    关于c++ - C++ Primer Plus:2D阵列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2938592/

    10-11 22:33