我刚刚开始学习 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: 12The 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;
}
- 您只需要在每月计数之外增加 absoluteTotal
- 您只需要一个一维数组来进行年度计数。
当涉及到此类事情时,先将它们写在纸上会有所帮助。
关于C++ 入门加 : 2D Arrays,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2938592/