蓝桥杯 矩阵乘法
程序员文章站
2022-03-16 18:25:23
...
题目大意
完整代码
#include<iostream>
#include<cstdio>
#include<cstring>
#define N 30
using namespace std;
int main() {
int A[N][N],B[N][N],C[N][N];
int n, m;
while (cin >> n >> m) {
memset(A, 0, sizeof(A));//初始化矩阵A,为n阶单位矩阵
for (int i = 0; i < n; i++) {
A[i][i] = 1;
}
for (int i = 0; i < n; i++) {//输入要进行次方的矩阵给B
for (int j = 0; j < n; j++) {
cin >> B[i][j];
}
}
while (m--) {//进行m次乘法
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
C[i][j] = 0;//初始化c的每个元素
for(int k = 0; k < n; k++){
//矩阵乘法等于第一个矩阵的行元素和第二个矩阵的列元素乘积和
//c矩阵作为零时存储矩阵
C[i][j] += A[i][k] * B[k][j];
}
}
}
//把C矩阵赋给A
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
A[i][j] = C[i][j];
}
}
}
//输出
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (j != n - 1)
cout << A[i][j] << " ";
else
cout << A[i][j];
}
cout << endl;
}
}
}