矩阵乘法不起作用

Matrix Multiplication doesn't work

本文关键字:不起作用      更新时间:2023-10-16

下面是我C++ 2 个矩阵相乘的代码。第一个输入是维度:所以矩阵 1 的行和列以及矩阵 2 的行和列。然后你需要输入两个矩阵的所有元素。完成后,应将 2 个矩阵相乘,并显示结果矩阵。但是,由于一个原因,在我输入所有元素后,它被卡住了。你们中有人明白我做错了什么吗?

#include <iostream>
#include "Matrix_functions.hpp"
using namespace std;    
int read_matrix(int** matrix, int rows, int cols)
{
    for(int i = 0; i < rows; i++)
    {
        matrix[i] = new int[cols];
        for(int j = 0; j < cols; j++)
        {
            cin >> matrix[i][j];
        }
    }
    return **matrix;
} 
int print_matrix(int** result, int rows, int cols)
{
    for(int i = 0; i < rows; i++)
    {
        for(int j = 0; j < cols; j++)
        {
            cout << result[i][j];
        }
    }
    cout << endl;
    return **result;
}
int multiply_matrix(int** matrix, int rows, int cols, int** matrix1, int rows1, int    cols1, int** result)
{
    for(int i = 0; i < rows; i++)
    {
        for(int j = 0; j < cols1; j++)
        {
            result[i][j] = 0;
            for(int k = 0; k < cols; k++)
            {
                result[i][j] = result[i][j] + (matrix[i][k] * matrix1[k][j]);
            }
        }
    }
    return **result;
 }
int main ()
{
    //matrices and dimensions
    int rows1, cols1, rows2, cols2;
    int **matrix1, **matrix2, **result = 0;
    cout << "Enter matrix dimensions" << endl;
    cin >> rows1 >> cols1 >> rows2 >> cols2;
    cout << "Enter a matrix" << endl;
    matrix1 = new int*[rows1];
    // Read values from the command line into a matrix
    read_matrix(matrix1, rows1, cols1);
    cout << "Enter a matrix" << endl;
     matrix2 = new int*[rows2];
    read_matrix(matrix2, rows2, cols2);
    // Multiply matrix1 one and matrix2, and put the result in matrix result
    multiply_matrix(matrix1, rows1, cols1, matrix2, rows2, cols2, result);
    print_matrix(result, rows1, cols2);
    //TODO: free memory holding the matrices
    return 0;
}

此外,现在,我的矩阵被打印为一维水平向量(1 2 3 4)而不是矩阵(1 2和3 4)。任何人都可以解释我如何解决这个问题?

multiply_matrix(matrix1, rows1, cols1, matrix2, rows2, cols2, result); 
`new` for result? Forgot?

像这样:

result = new int*[rows1];
for(int i = 0; i < rows1; i++)
{
   result[i] = new int[cols2];
}
multiply_matrix(matrix1, rows1, cols1, matrix2, rows2, cols2, result); 

尚未为result矩阵分配内存。
因此,您是未定义行为的受害者。

关于以矩阵形式打印,您需要打印换行符。

无需从读取和乘法函数返回元素。

另外,检查两个矩阵相乘的有效性,即乘法前cols1 == rows2

如果要将矩阵打印在不同的行上,请打印换行符。 执行此操作C++方法是使用 std::endl。

for(int i = 0; i < rows; i++)
{
    for(int j = 0; j < cols; j++)
    {
        cout << result[i][j];
    }
    cout << endl; ///< ADD THIS LINE
}