我目前正在尝试编写一个程序,该程序使用一个函数,该函数采用3个不同的10x10数组作为参数,并用前两个数组的乘积填充第三个数组。
我已经在网上搜索过,试图自己解决这个问题,但到目前为止,我只想出了这个:
(我用2填充了第一个数组,用3填充了第二个数组)
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
/************************************************
** Function: populate_array1
** Description: populates the passed array with 2's
** Parameters: 10x10 array
** Pre-Conditions:
** Post-Conditions:
*************************************************/
void populate_array1(int array[10][10])
{
int i, n;
for (i = 0; i<10; i++)
{
for (n = 0; n<10; n++)
{
array[i][n] = 2;
}
}
}
/************************************************
** Function: populate_array2
** Description: populates the passed array with 3's
** Parameters: 10x10 array
** Pre-Conditions:
** Post-Conditions:
*************************************************/
void populate_array2(int array[10][10])
{
int i, n;
for (i = 0; i<10; i++)
{
for (n = 0; n<10; n++)
{
array[i][n] = 3;
}
}
}
/************************************************
** Function: multiply_arrays
** Description: multiplies the first two arrays,
and populates the 3rd array with the products
** Parameters: 3 10x10 arrays
** Pre-Conditions:
** Post-Conditions:
*************************************************/
void multiply_arrays(int array1[10][10], int array2[10][10], int array3[10][10])
{
int i, n, j;
for (i = 0; i<10; i++)
{
for (n = 0; n<10; n++)
{
for (j = 0; j<10; j++)
{
array3[i][n] += array1[i][j]*array2[j][n];
}
}
}
}
int main()
{
int array1[10][10];
int array2[10][10];
int array3[10][10];
populate_array1(array1); // Fill first array with 2's
populate_array2(array2); // Fill second array with 3's
multiply_arrays(array1, array2, array3);
cout << array1[5][2];
cout << endl << array2[9][3];
cout << endl << array3[8][4];
return 0;
}据我所知,这应该是可行的,但是每当我打印第三个数组中的任何一个单元格时,我都得不到60,如下所示:

任何帮助都将不胜感激。
发布于 2013-04-15 09:36:10
您需要将array3中的所有值初始化为0。这不是为你做的。如果你不这样做,你就会使用一个随机值作为你的初始值。
发布于 2013-04-15 09:46:48
将array3初始化为zero的另一个选项是
int array3[10][10] = {{}};发布于 2013-04-15 09:36:28
您没有初始化array3,因此您在array3中得到了随机值,请尝试添加此函数:
void populate_array3(int array[10][10])
{
int i, n;
for (i = 0; i<10; i++)
{
for (n = 0; n<10; n++)
{
array[i][n] = 0;
}
}
}并在main中调用它
populate_array3(array3); https://stackoverflow.com/questions/16006370
复制相似问题