怎样用For循环编写两矩阵的乘积?
假设一个是四行三列的矩阵a,一个是三行四列的矩阵b,最后将它们的乘积存入一个数组c中!
for (i=0;i<4;i++) for (j=0;j<4;j++) sum+=a[i][j]*b[j][i]; c[i][j]=sum;
可是这只能实现c矩阵的第一个元素,其它的就不知道怎么实现了!
有谁知道,请帮我一下!谢谢!
#include<stdio.h>
int main()
{ int i,j,k=1; int a[4][4]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; int b[4][4]={21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36}; int c[4][4]; for (i=0;i<4;i++) for (j=0;j<4;j++,k++) { printf(" %3d",c[i][j]=a[i][j]*b[i][j]); if(k%4==0) puts(" "); }
/*
后经改进,觉得比上一次精简了许多。
*/
#include<stdio.h>
int main()
{ int i,j; int a[4][4]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; int b[4][4]={21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36}; for (i=0;i<4;i++) { for (j=0;j<4;j++) printf("%4d",a[i][j]*b[i][j]); puts(" "); }
/*
用楼主的思路也可以。
今天是不是睡不着觉了,我怎么这么兴奋?疑惑ing~~
*/
#include<stdio.h>
int main()
{ int i,j,sum; int a[4][4]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}; int b[4][4]={21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36}; int c[4][4]; for (i=0;i<4;i++) { for (j=0;j<4;j++) { sum=a[i][j]*b[i][j]; c[i][j]=sum; printf("%4d",c[i][j]); } puts(" "); }