用c语言实现求矩阵X的三元组表
时间: 2024-05-05 07:20:06 浏览: 20
好的,以下是用C语言实现求矩阵X的三元组表的代码:
```c
#include <stdio.h>
#define ROWS 3
#define COLS 3
void print_triplet(int triplet[][3], int count) {
printf("行 列 值\n");
for (int i = 0; i < count; i++) {
printf("%d %d %d\n", triplet[i][0], triplet[i][1], triplet[i][2]);
}
}
void matrix_to_triplet(int matrix[][COLS], int row, int col, int triplet[][3], int* count) {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (matrix[i][j] != 0) {
triplet[*count][0] = i;
triplet[*count][1] = j;
triplet[*count][2] = matrix[i][j];
(*count)++;
}
}
}
}
int main() {
int matrix[ROWS][COLS] = {
{1, 0, 0},
{0, 2, 0},
{0, 0, 3}
};
int triplet[ROWS * COLS][3];
int count = 0;
matrix_to_triplet(matrix, ROWS, COLS, triplet, &count);
print_triplet(triplet, count);
return 0;
}
```
运行结果为:
```
行 列 值
0 0 1
1 1 2
2 2 3
```
解释一下代码:
1. `print_triplet`函数用于打印三元组表,输入参数为一个二维数组和数组中元素的个数。
2. `matrix_to_triplet`函数用于将矩阵转换成三元组表,输入参数为矩阵、矩阵的行数、列数、一个二维数组和一个指向计数器的指针。该函数会将矩阵中所有非零元素的行、列和值存储到三元组表中,并更新计数器的值。
3. 在`main`函数中,我们定义了一个`3x3`的矩阵`matrix`,以及一个大小为`9x3`的数组`triplet`用于存储三元组表,还定义了一个计数器`count`,初值为`0`。
4. 调用`matrix_to_triplet`函数,将矩阵`matrix`转换为三元组表,并将转换后的结果存储到`triplet`数组中。
5. 调用`print_triplet`函数,打印三元组表。
希望能够解答您的问题!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)