题解 | #矩阵乘法#

矩阵乘法

http://www.nowcoder.com/practice/ebe941260f8c4210aa8c17e99cbc663b

#include <bits/stdc++.h>

using namespace std;

int main(){
    //输入
    int firstRows = 0;
    int firstCols = 0;
    int secondRows = 0;
    int secondCols = 0;
    cin >> firstRows;
    cin >> firstCols;
    secondRows = firstCols;
    cin >> secondCols;
    
    int num = 0;//矩阵元素
    //输入第一个矩阵
    vector<vector<int>> firstMatrix(firstRows, vector<int>(firstCols, 0));    
    for(int i = 0; i < firstRows; i++){
        for(int j = 0; j < firstCols; j++){
            cin >> num;
            firstMatrix[i][j] = num;
        }
    }
    //输入第二个矩阵
    vector<vector<int>> secondMatrix(secondRows, vector<int>(secondCols, 0));
    for(int i = 0; i < secondRows; i++){
        for(int j = 0; j < secondCols; j++){
            cin >> num;
            secondMatrix[i][j] = num;
        }
    }
    
    //计算相乘结果矩阵
    vector<vector<int>> mulRes(firstRows, vector<int>(secondCols, 0));
    for(int i = 0; i < firstRows; i++){
        for(int j = 0; j < secondCols; j++){
            
            for(int k = 0; k < firstCols; k++){
                mulRes[i][j] += firstMatrix[i][k] * secondMatrix[k][j]; //相乘相加
            }
           
        }
    }
    
    //输出
    for(int i = 0; i < firstRows; i++){
        for(int j = 0; j < secondCols; j++){
            cout << mulRes[i][j] << " ";
        }
        cout << endl; //换行,输出矩阵的下一行元素
    }
    
    return 0;
}
华为题库题解 文章被收录于专栏

牛客华为题库的题解

全部评论

相关推荐

2025-12-17 12:08
门头沟学院 产品经理
牛客85811352...:1希音不知道算不算大厂 2完全符合,过得很舒服, 3确实只有杂活 领导找我续签到明年3、4月我要继续吗。主要是边实习边秋招这段时间还是有点累
什么是优秀的实习经历
点赞 评论 收藏
分享
01-11 08:47
门头沟学院 Java
choumoduji...:读研的目的就是为了以最快的速度和最低的要求完成“学校”规定的毕业标准,而不是所谓课题组的要求
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务