2013-04-27 50 views
0

我正在嘗試創建一個計算每年總圖書銷售額的循環。我還需要計算過去三年的圖書銷售總額。使用for循環和二維數組的C++求和

我已經算出瞭如何計算所有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; 
+0

使用了'namonths'作爲'string'和數組索引 - 這是否甚至編譯? – 2013-04-27 09:34:14

回答

1
  1. 添加存儲每年的資金一個新的變量: int sumPerYear[years];
  2. 兩者之間的發言: 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;
0

這裏試試這個。 sumperYear是最初爲零的變量。在外循環的每個迭代中,將顯示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; }