用C++写一个求矩阵的逆矩阵的算法,其中,输入参数为原矩阵A,输出参数为原矩阵的逆矩阵B
时间: 2024-06-09 07:12:25 浏览: 5
好的,以下是一个用C语言实现的求矩阵的逆矩阵的算法,算法采用高斯-约旦消元法:
```c
#include <stdio.h>
#define N 3 // 矩阵维数
// 打印矩阵
void print_matrix(double matrix[N][N]) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
printf("%.2f ", matrix[i][j]);
}
printf("\n");
}
}
// 高斯-约旦消元法求逆矩阵
int inverse_matrix(double matrix[N][N], double inverse[N][N]) {
// 构造增广矩阵
double augment[N][2 * N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
augment[i][j] = matrix[i][j];
augment[i][j + N] = i == j ? 1.0 : 0.0;
}
}
// 消元过程
for (int k = 0; k < N; k++) {
double pivot = augment[k][k];
if (pivot == 0.0) {
return 1; // 矩阵不可逆
}
for (int j = 0; j < 2 * N; j++) {
augment[k][j] /= pivot;
}
for (int i = 0; i < N; i++) {
if (i == k) {
continue;
}
double factor = augment[i][k];
for (int j = 0; j < 2 * N; j++) {
augment[i][j] -= factor * augment[k][j];
}
}
}
// 提取逆矩阵
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
inverse[i][j] = augment[i][j + N];
}
}
return 0; // 成功
}
int main() {
double matrix[N][N] = {{1.0, 2.0, 3.0},
{2.0, 4.0, 5.0},
{3.0, 5.0, 6.0}};
double inverse[N][N];
printf("原矩阵:\n");
print_matrix(matrix);
if (inverse_matrix(matrix, inverse) == 0) {
printf("逆矩阵:\n");
print_matrix(inverse);
} else {
printf("矩阵不可逆\n");
}
return 0;
}
```
在这个代码中,我们首先定义了一个 `print_matrix` 函数,用于打印矩阵。接着,我们定义了一个 `inverse_matrix` 函数,用于求矩阵的逆矩阵。该函数的输入参数为原矩阵 `matrix`,输出参数为逆矩阵 `inverse`。该函数的实现采用了高斯-约旦消元法。最后,我们在 `main` 函数中调用 `inverse_matrix` 函数并打印结果。
注意,由于矩阵的可逆性与行列式的值有关,我们在实现中没有直接判断矩阵是否可逆,而是通过返回值来表示操作是否成功。如果返回值为 0,则表示操作成功,逆矩阵存储在 `inverse` 中;如果返回值为 1,则表示矩阵不可逆。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)