矩阵乘法

计算两个矩阵的乘积

http://www.nowcoder.com/questionTerminal/ed6552d03e624ba58d16af6d57e1c3e9

#include <iostream>
#include <cstdio>

using namespace std;

struct Matrix {
  int matrix[3][3];
  int row, col;
  Matrix();
  Matrix(int r, int c) : row(r), col(c){
  }
};

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

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

int main() {
  Matrix x(2, 3);
  Matrix y(3, 2);
  for (int i = 0; i < x.row; ++i) {
    for (int j = 0; j < x.col; ++j) {
      scanf("%d", &x.matrix[i][j]);
    }
  }
  for (int i = 0; i < y.row; ++i) {
    for (int j = 0; j < y.col; ++j) {
      scanf("%d", &y.matrix[i][j]);
    }
  }
  Matrix answer = Multiply(x, y);
  PrintMatrix(answer);
  return 0;
}
全部评论

相关推荐

点赞 评论 收藏
分享
头像
11-21 11:39
四川大学 Java
是红鸢啊:忘了还没结束,还有字节的5k 违约金
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务