首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在C++中将两个10x10数组相乘?

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

Stack Overflow用户
提问于 2013-04-15 09:32:27
回答 4查看 4.2K关注 0票数 2

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

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

(我用2填充了第一个数组,用3填充了第二个数组)

代码语言:javascript
复制
#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,如下所示:

任何帮助都将不胜感激。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2013-04-15 09:36:10

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

票数 8
EN

Stack Overflow用户

发布于 2013-04-15 09:46:48

将array3初始化为zero的另一个选项是

代码语言:javascript
复制
int array3[10][10] = {{}};
票数 4
EN

Stack Overflow用户

发布于 2013-04-15 09:36:28

您没有初始化array3,因此您在array3中得到了随机值,请尝试添加此函数:

代码语言:javascript
复制
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中调用它

代码语言:javascript
复制
populate_array3(array3); 
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16006370

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档