windlx实现俩个矩阵相乘循环的完整代码
时间: 2023-08-17 16:18:47 浏览: 125
两个矩阵相乘的实现程序
5星 · 资源好评率100%
好的,以下是一个使用循环实现两个矩阵相乘的完整代码:
```c
#include <stdio.h>
int main()
{
int row1, col1, row2, col2, i, j, k;
float a[100][100], b[100][100], c[100][100], sum;
printf("Enter the number of rows and columns of matrix 1: ");
scanf("%d %d", &row1, &col1);
printf("Enter the elements of matrix 1:\n");
for(i=0; i<row1; i++)
{
for(j=0; j<col1; j++)
{
scanf("%f", &a[i][j]);
}
}
printf("Enter the number of rows and columns of matrix 2: ");
scanf("%d %d", &row2, &col2);
if(col1 != row2)
{
printf("Error! The number of columns of matrix 1 should be equal to the number of rows of matrix 2.");
return 0;
}
printf("Enter the elements of matrix 2:\n");
for(i=0; i<row2; i++)
{
for(j=0; j<col2; j++)
{
scanf("%f", &b[i][j]);
}
}
// Multiplying matrices a and b and storing the result in matrix c
for(i=0; i<row1; i++)
{
for(j=0; j<col2; j++)
{
sum = 0;
for(k=0; k<col1; k++)
{
sum += a[i][k] * b[k][j];
}
c[i][j] = sum;
}
}
// Printing the result matrix c
printf("The result of matrix multiplication is:\n");
for(i=0; i<row1; i++)
{
for(j=0; j<col2; j++)
{
printf("%.2f ", c[i][j]);
}
printf("\n");
}
return 0;
}
```
该程序使用了三个嵌套的循环来实现矩阵相乘,其中外层循环控制结果矩阵c的行数,中间循环控制结果矩阵c的列数,内层循环则用来计算矩阵相乘的和。
阅读全文