2013-05-11 87 views
0

我期待完成此课程的课程。我在数组中遇到了问题,并且我已经阅读了所有的课程,书籍等。问题是如何在该位置增加一个二维数组元素?C++二维数组值增加

int main() 
{ 
int quantity, warehouse, product; 
int inventory[4][5] = { 
{900,400,250,95,153}, 
{52, 95, 625, 44, 250}, 
{100,720,301,50,878}, 
{325,650,57,445,584}, 
}; 
cout << "Enter the warehouse number between 1 and 4: " << endl; 
cin >> warehouse; 
cout << "Enter the product location between 1 and 5: " << endl; 
cin >> product; 
cout << "Enter the quantity delivered: " << endl; 
cin >> quantity;   

/* First the addition */ 
for(warehouse = 0; warehouse < 4; warehouse++) 
for(product = 0; product < 5; product++) 
inventory[warehouse][product] + quantity; 

cout << "The amount of units in warehouse " << warehouse << " is \n\n"; 


/* Then print the results */ 
for(warehouse = 0; warehouse < 4; warehouse++) { 
       for(product = 0; product < 5; product++) 
        cout << "\t" << inventory[warehouse][product]; 
       cout << endl; /* at end of each warehouse */ 
} 
return 0; 
} 

回答

1
for(warehouse = 0; warehouse < 4; warehouse++) 
for(product = 0; product < 5; product++) 
inventory[warehouse][product] + quantity; 

你不需要像这样迭代数组。摆脱那些for循环。用户输入warehouseproduct值。您只需访问该元素对应的元素,并添加到它:

inventory[warehouse][product] += quantity; 

注意使用+=。这实际上修改了数组中的值,而不是仅仅取值并将quantity添加到它。

接下来,它看起来像只打印出对应于warehouse的仓库的库存。要做到这一点,你不应该遍历所有的仓库,只有遍历产品:

for(product = 0; product < 5; product++) { 
    cout << "\t" << inventory[warehouse][product]; 
} 

这里的教训是,你只需要遍历一些元素,如果你需要做的是给每个其中。在第一种情况下,您只需将值添加到一个元素,因此不需要迭代。在第二种情况下,您需要打印出一行元素,因此您必须遍历该行。

+0

谢谢你们。这非常有意义,我的程序完美无缺。我想知道为什么阅读这本书是浪费时间。 – 2013-05-12 00:00:26

0
inventory[warehouse][product] + quantity; 

应该

inventory[warehouse][product] += quantity; 
//       ^^ 

+只返回此外,它不修改任何操作数。 a += ba = a + b同义。

这里也不需要for循环。这些值已经给出。

1

前两行后

/* First the Addition */ 

是uneccessary,好像你通过数组试图循环以获得您想要更改索引。这是没有必要的。

inventory[warehouse][product] += quantity; 

是你所需要的程序正常工作。它会将用户指定的数量添加到用户指定的索引。