矩阵的抽象数据类型定义(mooc笔记)

用二位数组存放矩阵,c语言实现矩阵的加法和乘法

代码如下:

#include
#include
#define MAXR 100    //矩阵最大行数
#define MAXC 100    //矩阵最大列数

typedef int ElementType;
typedef struct matrix* Matrix;

struct matrix{	//存放一个矩阵并记录行数列数
    int row;
    int col;
    ElementType Data[MAXC][MAXR];
};

Matrix Create(int M,int N); //返回一个M*N的矩阵
int GetMaxRow(Matrix A);    //返回矩阵A的总行数
int GetMaxCol(Matrix A);    //返回矩阵A的总列数
ElementType GetEntry(Matrix A,int i,int j); //返回矩阵A的第i行、第j列的元素
Matrix Add(Matrix A,Matrix B);  //如果A和B的行、列数一致,则返回矩阵C=A+B,否则返回错误标志
Matrix Multiply(Matrix A,Matrix B); //返回矩阵C=AB
void Print_Matrix(Matrix A);    //打印矩阵


int main(void){
    Matrix A,B,C,D;
    A = Create(3,3);
    B = Create(3,3);
    C = Add(A,B);
    D = Multiply(A,B);
    Print_Matrix(C);
    Print_Matrix(D);
    return 0;
}

Matrix Create(int M,int N){
    Matrix Ma = (Matrix)malloc(sizeof(struct matrix));
    Ma->row = M;
    Ma->col = N;

    for(int i = 0; i < M; i++)
        for(int j = 0; j < N; j++)
            scanf("%d",&Ma->Data[j][i]);	//一行一行写入数值

    return Ma;
}

int GetMaxRow(Matrix A){
    return A->row;
}

int GetMaxCol(Matrix A){
    return A->col;
}

ElementType GetEntry(Matrix A,int i,int j){
    return A->Data[j-1][i-1];   //先找列号,再找行号
}

Matrix Add(Matrix A,Matrix B){
    if(A->row != B->row || A->col != B->col){
        printf("Add error!\n");
        return NULL;
        }
    Matrix C = (Matrix)malloc(sizeof(struct matrix));
    C->row = A->row;
    C->col = A->col;

    for(int i = 0; i < C->col; i++)
        for(int j = 0; j < C->row; j++)
            C->Data[i][j] = A->Data[i][j] + B->Data[i][j];

    return C;
}

Matrix Multiply(Matrix A,Matrix B){
    if(A->row != B->row || A->col != B->col){
        printf("Multiply error!\n");
        return NULL;
        }
    Matrix C = (Matrix)malloc(sizeof(struct matrix));
    C->row = A->row;
    C->col = B->col;
    
    //模拟矩阵的乘法
    for(int i = 0; i < C->row; i++){
        for(int j = 0; j < C->col; j++){
            int temp = 0;
            for(int k = 0; k < A->col; k++){
                temp += A->Data[k][i]*B->Data[j][k];
                }
            C->Data[j][i] = temp;
            }
        }
    return C;
}

void Print_Matrix(Matrix A){
    for(int i = 0; i < A->row; i++){
        for(int j = 0; j < A->col; j++){
            printf("%4d",A->Data[j][i]);
            if(j == A->col - 1) printf("\n");
            }
        }
}

有什么没有考虑到的地方欢迎各位指出=-=

你可能感兴趣的:(数据结构,c语言)