2014-09-19 115 views
0

我想创建一个C++程序,它可以计算3年内销售的东西的数量。循环和二维数组的C++

我想用一个2维数组和一个循环(对于要求实践问题)做

,但不知何故,我不能让我的愿望的结果。计算和存储中有一些错误。你能帮我找出错误吗?

#include <iostream> 
#include <string> 
#include <array> 
using namespace std; 
int main(){ 
    int quantity[3][12]; 
    int sum[3]; 
    int *p; 
    p=sum; 
    int total; 
    int year=0; 
    string months[12]={ 
     "January", 
     "February", 
     "March", 
     "April", 
     "May", 
     "June", 
     "July", 
     "August", 
     "September", 
     "Octorber", 
     "November", 
     "December" 
    }; 
    for (int i=0; i<12; i++) { 
     cout<<"Enter the quantity sold in "<<months[i]<<endl; 
     cin>>quantity[year][i]; 
     if(i==11&&year<3){ 
      year++; 
      i=-1; 
     } 
    } 
    year=0; 
    for (int i=0; i<12; i++) { 
     sum[year]+=quantity[year][i]; 
     if (i==11&&year<3) { 
      i=(-1); 
      year++; 
     } 
    } 
    year=0; 
     for (int i=0; i<3; i++) { 
      cout<<"the information for year "<<(i+1)<<" is " <<endl; 
      for (int i1=0; i1<12; i1++) { 
       cout<<quantity[year][i1]<<endl; 
      } 
      cout<<"the sum of the "<< (i+1)<< " year: "<<sum[year]<<endl; 
      total+=sum[year]; 
     } 
    cout<<"the total amount sold in three year is "<<total<<endl; 

    return 0; 
} 
+0

*计算和存储中存在一些错误。*尚不清楚。指定确切的问题。 – 2014-09-19 04:19:17

回答

0

问题是,在本节:

year=0; 
     for (int i=0; i<3; i++) { 
      cout<<"the information for year "<<(i+1)<<" is " <<endl; 
      for (int i1=0; i1<12; i1++) { 
       cout<<quantity[year][i1]<<endl; 
      } 
      cout<<"the sum of the "<< (i+1)<< " year: "<<sum[year]<<endl; 
      total+=sum[year]; 
     } 
    cout<<"the total amount sold in three year is "<<total<<endl; 

    return 0; 
} 

它看起来像你认为你迭代年,而你实际上是迭代i和I1。为什么不使用蜜蜂使用的相同技巧而不是i1 for循环?

if (i==11&&year<3) { 
    i=(-1); 
    year++; 
} 
+0

非常感谢!我可以用相同的方法,但我试图用不同的方法解决这个问题,因为它是为了实践目的。再次感谢! – 2014-09-19 06:39:19

+0

您可以点击我的解决方案中的复选标记,表明这个问题解决了吗? – kilojoules 2014-09-19 18:01:11