题解 | #计算两个矩阵的乘积#

计算两个矩阵的乘积

https://www.nowcoder.com/practice/ed6552d03e624ba58d16af6d57e1c3e9

#include <iostream>

using namespace std;

struct Matrix {
    int matrix[3][3];
    int row, col;//行列
    Matrix(int r, int c) {
        row = r;
        col = c;
    }
};

Matrix multi(Matrix x, Matrix y) {
    Matrix c(x.row, y.col);
    for (int i = 0; i < c.row; i++) {
        for (int j = 0; j < c.col; j++) {
            c.matrix[i][j] = 0;
            for (int k = 0; k < x.col; k++) {
                c.matrix[i][j] += x.matrix[i][k] * y.matrix[k][j];
            }
        }
    }
    return c;
}

void printMatrix(Matrix a) {
    for (int i = 0; i < a.row; i++) {
        for (int j = 0; j < a.col; j++) {
            printf("%d ", a.matrix[i][j]);
        }
        printf("\n");
    }
}

int main() {
    Matrix a(2, 3);
    Matrix b(3, 2);
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 3; j++) {
            scanf("%d", &a.matrix[i][j]);
        }
    }
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 2; j++) {
            scanf("%d", &b.matrix[i][j]);
        }
    }
    Matrix ans = multi(a, b);
    printMatrix(ans);
    return 0;
}

全部评论

相关推荐

头像
11-09 17:30
门头沟学院 Java
TYUT太摆金星:我也是,好几个华为的社招找我了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务