c语言矩阵运算问题 紧急

2025-01-19 03:30:13
推荐回答(2个)
回答1:

#include
#include
#define X 3
#define Y 3

int a[X][Y];
int b[X][Y];
int c[X][Y];

void matrix(int b[][X],int c[][Y]);

main()
{
int i,j,temp;

printf("Please input int matrix b[%d][%d]\n",X,Y);
for(i=0;ifor(j=0;jscanf("%d",&temp);
b[i][j]=temp;
}
printf("Please input int matrix c[%d][%d]\n",X,Y);
for(i=0;ifor(j=0;jscanf("%d",&temp);
c[i][j]=temp;
}
matrix(b,c);
printf("Now print resource matrix b[%d][%d]=",X,Y);
for(i=0;iprintf("\n");
for(j=0;jprintf("%d ",b[i][j]);
}
printf("\n");
printf("Now print resource matrix c[%d][%d]=",X,Y);
for(i=0;iprintf("\n");
for(j=0;jprintf("%d ",c[i][j]);
}
printf("\n");
printf("Now printm multiply results matrix a[%d][%d]=B*C:",X,Y);
for(i=0;iprintf("\n");
for(j=0;jprintf("%d ",a[i][j]);
}
getchar();
return 0;
}
void matrix(int b[][X],int c[][Y])
{
int i,j,k;
for(i=0;ifor(j=0;jfor(k=0;ka[i][j]+=b[i][k]*c[k][j];
}
}

回答2:

#include
#include

typedef struct Matrix{
int *m;
int col;
int row;
};

Matrix* ConsMatrix(int *a,int cn,int rn){
Matrix *ma=(Matrix*)malloc(sizeof(Matrix));
ma->m=a;
ma->col=cn;
ma->row=rn;
return ma;
}

void PrintMatrix(Matrix *ma){
int i,j;
for(i=0;irow;i++){
for(j=0;jcol;j++){
printf("%d ",ma->m[i*(ma->col)+j]);
}
printf("\n");
}
}

Matrix* MatrixSub(Matrix*ma,Matrix*mb){
Matrix *mc=(Matrix*)malloc(sizeof(Matrix));

if(ma->col==mb->col&&ma->row==mb->row){

int size=ma->row*ma->col;
int i;
int *d=(int*)malloc(sizeof(int)*size);
mc->m=d;
mc->row=ma->row;
mc->col=ma->col;
for(i=0;i mc->m[i]=ma->m[i]-mb->m[i];
}
return mc;
}
printf("row or col cant match");
return NULL;
}

int main(){
int a[6]={1,2,3,4,5,6};
int b[6]={2,3,4,5,6,7};
Matrix *mb=ConsMatrix(b,2,3);
Matrix *ma=ConsMatrix(a,2,3);
Matrix *mc=MatrixSub(mb,ma);
PrintMatrix(mc);
system("pause");
return 1;
}