代码:
//矩阵计算器
#include <stdio.h>
void getmatrix(int m, int n, double m1[][n], double m2[][m]);
void calculate(int m, int n, double m1[][n], double m2[][m], double ansm[][m]);
void display(int m, int n, double m1[][n], double m2[][m], double ansm[][m]);
int main(void)
{
int m, n;
printf("Enter the size of the matrix:\n");
printf("The number of rows:");
scanf("%d", &m);
printf("The number of columns:");
scanf("%d", &n);
const int m1[m][n];
const int m2[n][m];
int ansm[m][m];
getmatrix(m, n, m1, m2);
calculate(m, n, m1, m2, ansm);
display(m, n, m1, m2, ansm);
return 0;
}
void getmatrix(int m, int n, double m1[][n], double m2[][m])
{
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
printf("Enter one number to complete matrix1:");
scanf("%lf", &m1[i][j]);
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
printf("Enter one number to complete matrix2:");
scanf("%lf", &m2[i][j]);
}
}
}
void calculate(int m, int n, double m1[][n], double m2[][m], double ansm[][m])
{
int sum = 0;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < m; j++)
{
for (int k = 0; k < n; k++)
{
sum += m1[i][k] * m2[k][j];
}
ansm[i][j] = sum;
sum = 0;
}
}
}
void display(int m, int n, double m1[][n], double m2[][m], double ansm[][m])
{
printf("\nmatrix1:\n");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
printf("%6.1f", m1[i][j]);
}
printf("\n");
}
printf("\nmatrix2:\n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < m; j++)
{
printf("%6.1f", m2[i][j]);
}
printf("\n");
}
printf("\nThe answer of calculation:\n");
for (int i = 0; i < m; i++)
{
for (int j = 0; j < m; j++)
{
printf("%6.1f", ansm[i][j]);
}
printf("\n");
}
}
核心:
两个矩阵计算的算法:
int sum = 0;
for (int i = 0; i < m; i++)
{
for (int j = 0; j < m; j++)
{
for (int k = 0; k < n; k++)
{
sum += m1[i][k] * m2[k][j];
}
ansm[i][j] = sum;
sum = 0;
}
}