首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

C 語言矩陣操作完整實現:生成、顯示、相加

     編輯:程式設計疑難解答

題目要求

補全矩陣生成 A、B、顯示、相加函數,輸出指定格式結果。矩陣維度 3×4。

完整代碼

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

typedef struct {
    int *pMat;
    int row, col;
} MAT, *pMAT;

typedef char *string;

void CreateMatA(pMAT a);
void CreateMatB(pMAT a);
void ShowMat(string str, pMAT a);
void MatAdd(pMAT a, pMAT b, pMAT c);

void main() {
    int m = 3, n = 4;
    MAT A = {0, m, n}, B = {0, m, n};
    pMAT C = (pMAT)malloc(sizeof(MAT));

    CreateMatA(&A);
    CreateMatB(&B);
    MatAdd(&A, &B, C);
    ShowMat("A:", &A);
    ShowMat("B:", &B);
    ShowMat("C=A+B:", C);

    free(A.pMat);
    free(B.pMat);
    free(C->pMat);
    free(C);
    printf("Press any key to exit");
    getch();
}

void CreateMatA(pMAT a) {
    a->pMat = (int*)malloc(a->row * a->col * sizeof(int));
    for (int row = 0; row < a->row; row++) {
        int nV1 = (row + 1) * 10;
        for (int col = 0; col < a->col; col++) {
            int nV2 = col * 2;
            int offset = row * a->col + col;
            a->pMat[offset] = nV1 + nV2;
        }
    }
}

void CreateMatB(pMAT a) {
    a->pMat = (int*)malloc(a->row * a->col * sizeof(int));
    for (int row = 0; row < a->row; row++) {
        int nV1 = (row + 1) * 10;
        for (int col = 0; col < a->col; col++) {
            int nV2 = col * 1;
            int offset = row * a->col + col;
            a->pMat[offset] = nV1 + nV2;
        }
    }
}

void ShowMat(string str, pMAT a) {
    printf("%s\n", str);
    for (int row = 0; row < a->row; row++) {
        for (int col = 0; col < a->col; col++) {
            int offset = row * a->col + col;
            printf("%2d ", a->pMat[offset]);
        }
        printf("\n");
    }
    printf("\n");
}

void MatAdd(pMAT a, pMAT b, pMAT c) {
    c->row = a->row;
    c->col = a->col;
    c->pMat = (int*)malloc(a->row * a->col * sizeof(int));
    for (int row = 0; row < a->row; row++) {
        for (int col = 0; col < a->col; col++) {
            int offset = row * a->col + col;
            c->pMat[offset] = a->pMat[offset] + b->pMat[offset];
        }
    }
}

關鍵點

  • 一維數組模擬二維:索引 row * col + col(按行主序)。
  • 動態分配內存,使用後釋放避免洩漏。
  • 結構體傳指針避免拷貝開銷。

運行結果


A:
10 12 14 16
20 22 24 26
30 32 34 36

B:
10 11 12 13
20 21 22 23
30 31 32 33

C=A+B:
20 23 26 29
40 43 46 49
60 63 66 69

代碼結構清晰,符合題目所有約束條件。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved