学会计算 矩阵C = A×B
核心代码:
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
for(int k = 0; k < n; ++k){ //矩阵C = 矩阵A × 矩阵B:
C[i][j] += A[i][k]*B[k][j]; //C[i][j] = A的第i行×B的第j列所有对应元素
}
}
}
答案:
#include <iostream>
#include <cstring>
using namespace std;
const int N = 11;
int A[N][N],B[N][N],C[N][N];
int main() {
int n,m; //n为矩阵的阶,m为矩阵的幂
cin >> n >> m;
memset(A,0,sizeof(A));
//输入矩阵A
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
cin >> A[i][j];
}
}
//计算m次幂
//(1)若m为1,输出原矩阵
if(m == 1){
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
cout << A[i][j] << " ";
}
cout << endl;
}
return 0;
}
//(2)若m>1,计算 矩阵 C = A×B
memcpy(B,A,sizeof(A));
while(--m){
memset(C,0,sizeof(C));
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
for(int k = 0; k < n; ++k){ //矩阵C = 矩阵A × 矩阵B:
C[i][j] += A[i][k]*B[k][j]; //C[i][j] = A的第i行×B的第j列所有对应元素
}
}
}
memcpy(B,C,sizeof(C)); //这次的幂次运算结果C赋值给B
}
//输出矩阵C
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j){
cout << C[i][j] << " ";
}
cout << endl;
}
return 0;
}