题解 | #矩阵乘法#

矩阵乘法

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;
}
华为题库题解 文章被收录于专栏

牛客华为题库的题解

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务