数据结构与算法 ~ 数组和广义表 ~ 矩阵的相乘

数据结构与算法中数组和广义表的矩阵的相乘.

#include<stdlib.h>
#include<stdio.h>
#define MAX 10
struct elem{
	int  data;/*元素值*/
};
typedef struct elem Elem;

struct matrix{
	int row;/*行数*/
	int col; /*列数*/
	Elem  array[MAX][MAX];
};
typedef  struct matrix Matrix;

void CreateMatrix(Matrix  *m){
  int i,j,k;
  int r,c,e;
  printf("\n 请输入行列值(最大10*10):");
  scanf("%d%d",&r,&c);
  if (r>10||c>10) printf("\n输入错误!");
  else {
	  m->row=r;
	  m->col=c;
	  printf("\n请输入数值\n");
	  for(i=0;i<m->row;++i)
		  for(j=0;j<m->col;++j){
			   printf("[%d][%d]=\t",i,j);
			   scanf("%d",&e);
			  m->array[i][j].data=e;
		  }/*for*/
  }/*else*/
}/*createMatrix*/

void PrintMatrix(Matrix  *m){
  int i,j;
  printf("\n当前矩阵是[%d x %d]:",m->row,m->col);
  for(i=0;i<m->row;++i){
	  printf("\n");
	  for(j=0;j<m->col;++j)
		  printf("%5d",m->array[i][j].data);
      }/*for*/
}/*PrintMatrix*/

void MatrixMulti(Matrix *ma,Matrix *mb,Matrix *mc){
  int i,j,k;
  if (ma->col!=mb->row)/*两个矩阵能否相乘进行判断*/
	  printf("\n两个矩阵不匹配,不能相乘!");
 else {
            mc->row=ma->row;   /*输入矩阵规模参数*/
            mc->col=mb->col;
            for(i=0;i<mc->row;++i)
                 for(j=0;j<mc->col;++j){
                    mc->array[i][j].data=0;
                    for(k=0;k<ma->col;++k)
                       mc->array[i][j].data+=ma->array[i][k].data*mb->array[k][j].data;
                  }/*for*/
          }/*else*/
}/*mul*/

int main(){
  int i,j,k;
  Matrix a,b,c;
  CreateMatrix(&a);
  CreateMatrix(&b);
  PrintMatrix(&a);
  PrintMatrix(&b);
  MatrixMulti(&a,&b,&c);
  PrintMatrix(&c);
  system("pause");
  exit(0);
} 

运行结果是:


 请输入行列值(最大10*10):3 4

请输入数值
[0][0]= 2
[0][1]= 4
[0][2]= 6
[0][3]= 7
[1][0]= 8
[1][1]= 9
[1][2]= 1
[1][3]= 3
[2][0]= 5
[2][1]= 11
[2][2]= 15
[2][3]= 23

 请输入行列值(最大10*10):4 6

请输入数值
[0][0]= 2
[0][1]= 3
[0][2]= 4
[0][3]= 5
[0][4]= 6
[0][5]= 7
[1][0]= 8
[1][1]= 9
[1][2]= 1
[1][3]= 11
[1][4]= 22
[1][5]= 33
[2][0]= 44
[2][1]= 55
[2][2]= 66
[2][3]= 77
[2][4]= 88
[2][5]= 99
[3][0]= 10
[3][1]= 12
[3][2]= 14
[3][3]= 16
[3][4]= 18
[3][5]= 20

当前矩阵是[3 x 4]:
    2    4    6    7
    8    9    1    3
    5   11   15   23
当前矩阵是[4 x 6]:
    2    3    4    5    6    7
    8    9    1   11   22   33
   44   55   66   77   88   99
   10   12   14   16   18   20
当前矩阵是[3 x 6]:
  370  456  506  628  754  880
  162  196  149  264  388  512
  988 1215 1343 1669 2006 2343
请按任意键继续. . .

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值