Bootstrap

C语言实现两个矩阵相乘

#include<stdio.h>
#define M 3
#define N 3

int main(void)
{
	//定义三个数组,第三个存放结果 均初始化为0
	int array1[M][N] = { 0 };
	int array2[M][N] = { 0 };
	int array3[M][N] = { 0 };
	int m ,i,j;
	//构建矩阵1
	printf("第一个矩阵:\n");
	for ( i = 0; i < M; i++)
	{
		for ( j = 0; j < N; j++)
		{
			scanf_s("%d", &array1[i][j]);
		}
	}
	//构建矩阵2
	printf("第二个矩阵:\n");
	for (i = 0; i < M; i++)
	{

		for (j = 0; j < N; j++)
		{
			scanf_s("%d", &array2[i][j]);
		}
	}
		//实现矩阵相乘 要判断矩阵的行列是否可以相乘 
	   //矩阵1的行*矩阵2的列 对应相乘相加
		printf("矩阵相乘结果:\n");
		for (i = 0; i < M; i++)
		{
			for (int j = 0; j < N; j++)
			{
				int sum = 0;
				for (m = 0; m < 3; m++)
				{
					sum = sum + array1[i][j] * array2[j][i];
				}
				array3[i][j] = sum;
			}
		}
		for (i = 0; i < M; i++)
		{
			for (int j = 0; j < N; j++)
			{
				printf("%3d", array3[i][j]);
			}
			printf("\n");
		}

	}


;