c++ - 如何在 C++ 中将两个 10x10 数组相乘?

标签 c++ arrays multidimensional-array matrix-multiplication

我目前正在尝试编写一个程序,该程序使用一个函数,该函数将 3 个不同的 10x10 数组作为参数,并用前 2 个数组的乘积填充第 3 个数组。

我已经在网上搜索,试图自己解决问题,但到目前为止,我只想到了这个:

(我用 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,如下所示:

code output

如有任何帮助,我们将不胜感激。

最佳答案

您需要将 array3 中的所有值初始化为 0。这不是为您完成的。如果您不这样做,您将使用随机值作为初始值。

关于c++ - 如何在 C++ 中将两个 10x10 数组相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16006370/

相关文章:

c++ - Libusb - ubuntu - Psoc5。 libusb_open_device_with_vid_pid 返回 0

javascript - 如何使用 JavaScript 评估集合包含测试?

c++ - "char *var[3]"和 "char var[3][15]"有什么区别?

c++ - Xcode 应用程序不再从应用程序存储的文件夹中读取输入

c++ - 为什么 std::binary_search 的参数是前向迭代器?

javascript - Mongoose 数组推送失败

java - 二维数组上 ArrayIndexOutOfBoundsException 的快速帮助

python - 从具有最大 Lead_id 的多维数组获取数组(任何特定变量)

c++ - 无法在 STL 中打印一组 vector 的元素

php - 排序多维数组 (PHP) - 日期并发症和计数