0

嗨,任何人都可以帮我弄清楚我做错了什么。编写一个函数来执行矩阵乘法。我没有显示我的所有值。我真的很困惑。谢谢(对 C++ 非常陌生)

    int MultiplyTwoMatrices(int **MatrixA, int rowA, int ColumnA, int **MatrixB, int rowB,    int columnB);
int **Matrixmultiply;       //I have allocated and freed it's memory
int rowA=4;
int rowB=4;
int columnA=4;
int columnB=4;

int main()
{
for ( x = 0; x < rowA; x++)
{
    for (y = 0; y < columnB; y++)
    {
    Matrixmultiply[x][y] = MultiplyTwoMatrices(MatrixA,rowA,columnA,MatrixB,rowB,columnB);
        cout<<Matrixmultiply[x][y] <<"\t";

    }
    cout<<"\n";
}

int MultiplyTwoMatrices(int **MatrixA, int rowA, int ColumnA, int **MatrixB, int rowB,    int columnB)
{

int **temp = NULL;
int sum = 0;
double **Multiple = NULL;
int i=0, j=0;

temp = (int**)malloc(columnB*(sizeof(int*)));
for (int p=0; p<columnB; p++)
    {
        temp[p] = (int*)malloc(rowB*(sizeof(int))); 

    }

Multiple = (double**)malloc(rowA*(sizeof(double*)));
for (int p=0; p<rowA; p++)
    {
        Multiple[p] = (double*)malloc(columnB*(sizeof(double))); 

    }

for (int p =0; p<columnB; p++)
    {
        for (int q = 0; q<rowB; q++)
        {
            temp[p][q] = MatrixB[q][p];
        }

    }
for (i =0; i<rowA; i++)
    {
        for (j = 0; j<columnB; j++)
        {
            for (int r = 0; r<rowB; r++)
            {
            sum = sum + (MatrixA[i][r]  * temp[j][r]);
            }

            Multiple[i][j] = sum;
            return Multiple[i][j];
            //cout<<Multiple[i][j]<<"\t";
            sum=0;
        }
            //cout<<"\n";

    }


for (int p =0; p<columnB; p++)
    free (temp[p]);
    free(temp);
for (int p =0; p<rowA; p++)
    free (Multiple[p]);
    free(Multiple);
}
4

1 回答 1

0

好的,首先在您的代码中需要进行大量清理。保持函数自包含是一种很好的做法,因此只在函数中传递两个矩阵参数并在函数本身中进行所有迭代。对此的一个简单论点是效率,否则您的代码必须进行 n*m 函数调用,这不好。所以:

int MultiplyTwoMatrices(int **MatrixA, int **MatrixB){}

更好的是,您使用的是 C++ 而不是 C,因此请使用对象!将 int ** 封装在一个矩阵类中,这将使您的生活更轻松,您只需要传递对象引用而不是指针!

我强烈建议您阅读我推荐的书,因为您将充分利用 C++。

无论如何,问题是你在 for 循环中返回。当您返回函数时会停止,因此它不会遍历最终的 for 循环。

于 2013-02-23T20:59:51.300 回答