0

我希望完成这个课程的课程。当涉及到数组时,我迷失了方向,我已经阅读了所有课程作业、书籍等。问题是如何在该位置增加二维数组元素?

    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;
}
4

3 回答 3

1

后的前两行

/* First the Addition */

是不必要的,似乎您试图遍历数组以获取您想要更改的索引。那是不必要的。

inventory[warehouse][product] += quantity;

就是让程序正常工作所需要的一切。它将用户指定的数量添加到用户指定的索引中。

于 2013-05-11T21:05:13.197 回答
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];
}

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

于 2013-05-11T20:51:23.147 回答
0
inventory[warehouse][product] + quantity;

应该

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

唯一返回加法,+它不修改任何操作数。a += b是 的同义词a = a + b

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

于 2013-05-11T20:50:55.493 回答