C语言实现矩阵乘法


本文将使用C语言实现矩阵乘法;分别生成阶为m*n和p*q的两个矩阵,以得到阶为m*q的结果矩阵,其中n等于p。

示例代码:

#include <stdio.h>
 
void main(){
	int m=3, n=3, p=3, q=3, c, d, k, sum = 0;
	int first[m][n], second[p][q], multiply[m][q];

	first[0][0] = 1; first[0][1] = 2; first[0][2] = 0;
	first[1][0] = 0; first[1][1] = 1; first[1][2] = 1;
	first[2][0] = 2; first[2][1] = 0; first[2][2] = 1;

	second[0][0] = 1; second[0][1] = 1; second[0][2] = 2;
	second[1][0] = 2; second[1][1] = 1; second[1][2] = 1;
	second[2][0] = 1; second[2][1] = 2; second[2][2] = 1;

	if ( n != p ){
		printf("Matrices with entered orders can't be multiplied with each other.\n");
	}

	for(c=0;c<m;c++){
		for(d=0;d<q;d++){
			for(k=0;k<p;k++){
				sum = sum + first[c][k]*second[k][d];
			}
			multiply[c][d] = sum;
			sum = 0 ;
		}
	}

	printf("Product of entered matrices:\n");

	for(c=0;c<m;c++){
		for(d=0;d<q;d++){
			printf("%d\t", multiply[c][d]);
		}
		printf("\n");
	}

}

运行效果:


本文版权归作者所有!

如需转载,请注明出处;本文地址:https://www.perfcode.com/p/matrix-multiplication.html