【问题标题】:c++ summation using for loop and two dimensional arrayc++求和使用for循环和二维数组
【发布时间】:2013-04-27 09:31:40
【问题描述】:

我正在尝试创建一个循环来计算每年的图书总销售额。我还需要计算过去三年的总图书销售量。

我已经计算出如何计算所有 3 年的总和,但是,我在计算每年售出的总图书订单时遇到了麻烦。这是我目前所拥有的。

    const int months = 12;
    const int years =3;
    string namonths [months] = {"January", "February", "March", "April",
                 "May", "June", "July", "August", "September",
                 "October", "November", "December"};
int bookorders[years][months];
int sum=0;

for (int i = 0; i < years ; i++) {
for (int n = 0; n < months; n++) {

    std::cout << "Year " << i + 1 << " Month " << namonths[n] <<":"<< std::endl;

    cin >> bookorders[i][n];

    sum += bookorders[i][n];
}

}

//  std::cout << "total orders are for each year are: " << sum <<std::endl;
std::cout << "total orders are " << sum <<std::endl;

【问题讨论】:

  • 您使用 namonths 作为 string 和数组索引 - 这甚至可以编译吗?

标签: c++ arrays for-loop sum


【解决方案1】:
  1. 添加一个新变量来存储每年的总和: int sumPerYear[years];
  2. 在两个 for 语句之间: sumPerYear[i] = 0;
  3. 然后在 for 循环核心中说: sumPerYear[i] += bookorders[i][n];
  4. 终于在最后: for (int i = 0; i < years ; i++) std::cout << "year " << i << " sum: " << sumPerYear[i] << std::endl;

【讨论】:

    【解决方案2】:

    来试试这个。 sumperYear 是最初为零的变量。在外部的每次迭代中 for循环,将显示sumperYear。

    for (int i=0; i<years; i++) { for (int j=0 ; j< months; j++) { sumperYear+=bookOrders[i][j]; } cout<<"For the year:" << i+1 << " the total orders are: "<< sumperYear; sumperYear=0; }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      • 2015-10-02
      • 1970-01-01
      • 1970-01-01
      • 2019-06-02
      • 1970-01-01
      • 2013-08-02
      相关资源
      最近更新 更多