请写一个c语言完整代码,要求输入矩阵,输出该矩阵的逆矩阵
时间: 2024-06-10 10:04:26 浏览: 42
我可以听懂您的问题,下面是C语言的完整代码,实现输入矩阵,输出该矩阵的逆矩阵。
```
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* 求矩阵的逆 */
int matrix_inverse(double *input, int n, double *output) {
double *a, *b;
int *is, *js, l, k, i, j, m;
double d, p;
b = (double*) malloc(n * n * sizeof(double));
a = (double*) malloc(n * n * sizeof(double));
is = (int*) malloc(n * sizeof(int));
js = (int*) malloc(n * sizeof(int));
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
*(a + i * n + j) = *(input + i * n + j);
}
}
for (k = 0; k < n; k++) {
d = 0.0;
for (i = k; i < n; i++) {
for (j = k; j < n; j++) {
l = i * n + j;
p = fabs(*(a + l));
if (p > d) {
d = p;
is[k] = i;
js[k] = j;
}
}
}
if (d == 0.0) {
free(a);
free(b);
free(is);
free(js);
return 0;
}
if (is[k] != k) {
for (j = 0; j < n; j++) {
l = k * n + j;
m = is[k] * n + j;
p = *(a + l);
*(a + l) = *(a + m);
*(a + m) = p;
}
}
if (js[k] != k) {
for (i = 0; i < n; i++) {
l = i * n + k;
m = i * n + js[k];
p = *(a + l);
*(a + l) = *(a + m);
*(a + m) = p;
}
}
l = k * n + k;
*(b + l) = 1.0 / *(a + l);
for (j = 0; j < n; j++) {
if (j != k) {
m = k * n + j;
*(a + m) = *(a + m) * (*(b + l));
}
}
for (i = 0; i < n; i++) {
if (i != k) {
for (j = 0; j < n; j++) {
if (j != k) {
l = i * n + j;
*(a + l) = *(a + l) - *(a + i * n + k) * (*(a + k * n + j));
}
}
}
}
for (i = 0; i < n; i++) {
if (i != k) {
l = i * n + k;
*(a + l) = -*(a + l) * (*(b + k * n + k));
}
}
}
for (k = n - 1; k >= 0; k--) {
if (js[k] != k) {
for (j = 0; j < n; j++) {
l = k * n + j;
m = js[k] * n + j;
p = *(b + l);
*(b + l) = *(b + m);
*(b + m) = p;
}
}
if (is[k] != k) {
for (i = 0; i < n; i++) {
l = i * n + k;
m = i * n + is[k];
p = *(b + l);
*(b + l) = *(b + m);
*(b + m) = p;
}
}
}
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
*(output + i * n + j) = *(b + i * n + j);
}
}
free(a);
free(b);
free(is);
free(js);
return 1;
}
/* 测试 */
int main() {
int i, j, n;
double *input, *output;
printf("请输入矩阵的阶数:");
scanf("%d", &n);
input = (double*) malloc(n * n * sizeof(double));
output = (double*) malloc(n * n * sizeof(double));
printf("请输入矩阵的元素:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%lf", input + i * n + j);
}
}
if (matrix_inverse(input, n, output)) {
printf("逆矩阵为:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%lf ", *(output + i * n + j));
}
printf("\n");
}
} else {
printf("该矩阵没有逆矩阵!\n");
}
free(input);
free(output);
return 0;
}
```
当您输入矩阵及其阶数后,程序会将其存储,并调用matrix_inverse()函数计算逆矩阵,最后输出结果。注意,这段代码并没有处理除数为 0 的异常情况,所以请确保您输入的矩阵是可逆的。
阅读全文