152. 矩陣加法

 avatar
user_6817964
c_cpp
2 years ago
1.2 kB
1
Indexable
Never
typedef struct matrix {
    int row, col;
    int** data;
} *MATRIX;

int main() {
	MATRIX x = (struct matrix*)malloc(sizeof(struct matrix));
	MATRIX y = (struct matrix*)malloc(sizeof(struct matrix));

	scanf("%d%d", &x->row, &x->col);
	x->data = (int**)malloc(sizeof(int*) * x->row);
	for (int i = 0; i < x->row; i++) {
		x->data[i] = (int*)malloc(sizeof(int) * x->col);
	}

	for (int r = 0; r < x->row; r++) {
		for (int c = 0; c < x->col; c++) {
			scanf("%d", &x->data[r][c]);
		}
	}

	scanf("%d%d", &y->row, &y->col);
	y->data = (int**)malloc(sizeof(int*) * y->row);
	for (int i = 0; i < y->row; i++) {
		y->data[i] = (int*)malloc(sizeof(int) * y->col);
	}

	for (int r = 0; r < y->row; r++) {
		for (int c = 0; c < y->col; c++) {
			scanf("%d", &y->data[r][c]);
		}
	}

	if (x->col == y->col && x->row == y->row) {

		for (int r = 0; r < x->row; r++) {
			for (int c = 0; c < x->col; c++) {
				if (c == 0) {
					printf("%d", x->data[r][c] + y->data[r][c]);
				}
				else {
					printf(" %d", x->data[r][c] + y->data[r][c]);
				}
			}
			if (r != (x->row) - 1) {
				printf("\n");
			}
		}
	}
	else {
		printf("不可相加");
	}

	free(x->data);
	free(y->data);
	return 0;
}