gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:24:51 25 4
gpt4 key购买 nike

我目前正在尝试编写一个程序,该程序使用一个函数,该函数将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com