1、当两个输入矩阵的行数或列数不同时,认为两个矩阵无法进行相加,输出0。 2、当两个矩阵进行相加时,若相加后产生0的结果,则不计入TSMatrix中的data数组中。 3、注意每行输出后都有一个空格。
时间: 2024-12-18 09:34:44 浏览: 59
在C语言中,你可以创建一个名为`TSMatrix`的结构体来表示矩阵,然后定义一个函数`add_matrices`来处理矩阵的相加。这里是一个简单的实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int rows;
int cols;
int* data; // 存储矩阵元素的数组
} TSMatrix;
// 动态分配内存并初始化矩阵数据
TSMatrix* create_matrix(int rows, int cols) {
TSMatrix* mat = malloc(sizeof(TSMatrix));
mat->rows = rows;
mat->cols = cols;
mat->data = malloc(rows * cols * sizeof(int));
return mat;
}
// 清理矩阵内存
void free_matrix(TSMatrix* mat) {
free(mat->data);
free(mat);
}
// 矩阵相加
int add(int a, int b) {
return a + b;
}
// 检查矩阵是否需要添加结果
bool should_add(int result) {
return result != 0;
}
// 主函数示例,用于演示矩阵相加
void add_and_output(TSMatrix* mat1, TSMatrix* mat2) {
if (mat1->rows != mat2->rows || mat1->cols != mat2->cols) {
printf("0 ");
return;
}
for (int i = 0; i < mat1->rows; ++i) {
for (int j = 0; j < mat1->cols; ++j) {
int sum = add(mat1->data[i * mat1->cols + j], mat2->data[i * mat2->cols + j]);
if (should_add(sum)) {
mat1->data[i * mat1->cols + j] = sum;
} else {
// 不计入data数组
}
}
printf("%d ", mat1->data[i * mat1->cols]); // 输出当前行的数据,每个元素间用空格隔开
printf("\n"); // 行末换行
}
}
// 示例
int main() {
int rows = 3;
int cols = 3;
TSMatrix* mat1 = create_matrix(rows, cols);
// 初始化mat1的数据...
TSMatrix* mat2 = create_matrix(rows, cols);
// 初始化mat2的数据...
add_and_output(mat1, mat2);
free_matrix(mat1);
free_matrix(mat2);
return 0;
}
```
这个程序首先检查矩阵的尺寸是否匹配,如果不匹配则直接输出0。如果行数和列数匹配,它将计算并存储相加后的结果,但只有非零结果才会被实际保存。
阅读全文
相关推荐















