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

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

#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 MatrixAdd(Matrix *ma,Matrix *mb,Matrix *mc){
  int i,j,k;
  if ((ma->row!=mb->row) || (ma->col!=mb->col) )/*两个矩阵能否相加进行判断*/
      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=ma->array[i][j].data+mb->array[i][j].data;
          }/*else*/
}/*mul*/


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

运行结果:


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

请输入数值
[0][0]= 3
[0][1]= 4
[0][2]= 5
[0][3]= 6
[1][0]= 7
[1][1]= 8
[1][2]= 9
[1][3]= 7
[2][0]= 65
[2][1]= 43
[2][2]= 32
[2][3]= 21

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

请输入数值
[0][0]= 11
[0][1]= 22
[0][2]= 33
[0][3]= 44
[1][0]= 55
[1][1]= 66
[1][2]= 77
[1][3]= 88
[2][0]= 99
[2][1]= 68
[2][2]= 42
[2][3]= 71

当前矩阵是[3 x 4]:
    3    4    5    6
    7    8    9    7
   65   43   32   21
当前矩阵是[3 x 4]:
   11   22   33   44
   55   66   77   88
   99   68   42   71
当前矩阵是[3 x 4]:
   14   26   38   50
   62   74   86   95
  164  111   74   92
请按任意键继续. . .

 如果输入错误


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

请输入数值
[0][0]= 2
........................

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

请输入数值
[0][0]= 1
........................

当前矩阵是[3 x 4]:
    2    3    4    5
    6    7    8    9
    7    6    5    4
当前矩阵是[3 x 6]:
    1    1    1    1    1    1
    1    1    1    1    1    1
    1    1    1    1    1    1
两个矩阵不匹配,不能相加!
请按任意键继续. . .
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值