首页 > 解决方案 > 动态分配数组的矩阵乘法;结果不正确

问题描述

我一直在尝试调试这段代码,但是当它们位于动态分配的内存中时,我不确定如何在我的 IDE 中实际访问它们。该程序应该根据用户的输入初始化两个矩阵,然后尽可能将它们相乘。

我发现了一些错误并纠正了它们,但我不确定是什么导致了这个问题。

#include <iostream>
using namespace std;

typedef int* IntArrayPtr;

int main() {
    int r1, c1, r2, c2;
    do {
        //GET DIMENSIONS OF MATRICIES
        cout << "Welcome! This program takes two matricies and multiplies them together.\n"
            << "Enter the number of rows and number of columns for Matrix 1: ";
        cin >> r1 >> c1;
        cout << "Enter the number of rows and number of columns for Matrix 2: ";
        cin >> r2 >> c2;

        //DETECT IF MULTIPLICATION CAN HAPPEN
        if (r1 != c2) {
            cout << "Error: matricies cannot be multiplied. Please enter a new set.\n";
        }
    } while (r1 != c2); //have the user enter again if the rows and columns don't match
    cout << endl;

    //INTIALIZE MATRICIES USING DYNAMIC ARRAYS
    //intialize MATRIX 1
    IntArrayPtr *a = new IntArrayPtr[r1];
    cout << "For MATRIX 1: Enter the contained values. Press enter after each entry.\n";
    for (int i = 0; i < r1; i++) {
        a[i] = new int[c1]; //init columns for each row
        cout << "ROW" << i + 1 << "\n";
        for (int j = 0; j < c1; j++) {
            cin >> a[i][j]; //fill columns of rows
        }
        cout << endl;
    }
    //intialize MATRIX 2
    IntArrayPtr *b = new IntArrayPtr[r2];   //init rows
    cout << "For MATRIX 2: Enter the contained values. Press enter after each entry.\n";
    for (int i = 0; i < r2; i++) {
        b[i] = new int[c2]; //intialize columns
        cout << "ROW" << i + 1 << "\n";
        for (int j = 0; j < c2; j++) {
            cin >> b[i][j]; //fill columns of rows
        }
        cout << endl;
    }

    //INITIALIZE MATRIX TO STORE RESULT IN
    //matrix will have the rows of the first and columns of the second, according to matrix multiplication
    IntArrayPtr *c = new IntArrayPtr[r1]; //init rows
    for (int i = 0; i < r1; i++) {
        c[i] = new int[c2]; //init columns
    }

    //MULTIPLY MATRICIES
    for (int i = 0; i < r1; ++i) {
        for (int j = 0; j < c2; ++j) {
            for (int k = 0; k < c1; ++k) {
                c[i][j] += a[i][k] * b[k][j];
            }
        }
    }

    //PRINT RESULT
    for (int i = 0; i < r1; i++) {
        for (int j = 0; j < c2; j++) {
            cout << c[i][j] << " ";
        }
        cout << endl;
    }

    delete[] a; delete[] b; delete[] c;

    system("pause");
    return 0;
}

矩阵应该是乘法的结果,但是当我尝试使用小矩阵(例如 3 x 2 乘以 2 x 3)执行程序时,输出会吐出在我看来是垃圾的东西。我确定我的错误很愚蠢,但我们将不胜感激。

标签: c++

解决方案


您没有正确初始化矩阵 c 。试试这个

//INITIALIZE MATRIX TO STORE RESULT IN
//matrix will have the rows of the first and columns of the second, according to matrix multiplication
IntArrayPtr *c = new IntArrayPtr[r1]; //init rows
for (int i = 0; i < r1; i++) {
    c[i] = new int[c2]; //init columns
    for (int j = 0; j < c2; j++) {
        c[i][j] = 0;
    }
}

推荐阅读