C++ 入门加 : 2D Arrays

标签 c++ arrays loops multidimensional-array for-loop

我刚刚开始学习 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 的三个总数:

year 1: 12
year 2: 12
year 3: 12

The total number of books sold over a period of 3 years is: 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;
}
  1. 您只需要在每月计数之外增加 absoluteTotal
  2. 您只需要一个一维数组来进行年度计数。

当涉及到此类事情时,先将它们写在纸上会有所帮助。

关于C++ 入门加 : 2D Arrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2938592/

相关文章:

c++ - 将迭代器获取到泛型类 : HOW TO 中的泛型容器

c++ - 从 io_context 中删除工作或使用多个 io_context 对象

c++ - 使用 Array 填充 List<> 得到错误的数字

c - 如何将字符串数组传递给 C 中的另一个函数

c++ - 有效地 const_cast-ing 常量引用参数

arrays - 在 NodeJS 中将两个数组合并为一个

java - 以有效的方式获取所有可能的数组索引位置

javascript - JSON 提取的数据返回次数过多

c++ - 防止展开特定循环

python - 关于 python 中的迭代器