用c语言写Crout分解代码
时间: 2023-06-09 19:07:50 浏览: 110
以下是用C语言实现Crout分解的代码:
```c
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i, j, k;
float **A, **L, **U;
float sum;
printf("请输入矩阵的阶数:");
scanf("%d", &n);
// 初始化矩阵
A = (float **)malloc(n * sizeof(float *));
L = (float **)malloc(n * sizeof(float *));
U = (float **)malloc(n * sizeof(float *));
for (i = 0; i < n; i++) {
A[i] = (float *)malloc(n * sizeof(float));
L[i] = (float *)malloc(n * sizeof(float));
U[i] = (float *)malloc(n * sizeof(float));
}
printf("请输入%d个方程的系数矩阵:\n", n);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%f", &A[i][j]);
}
}
// 初始化L和U矩阵
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (j < i) {
L[j][i] = 0;
} else {
L[j][i] = A[j][i];
for (k = 0; k < i; k++) {
L[j][i] = L[j][i] - L[j][k] * U[k][i];
}
}
}
for (j = 0; j < n; j++) {
if (j < i) {
U[i][j] = 0;
} else if (j == i) {
U[i][j] = 1;
} else {
U[i][j] = A[i][j] / L[i][i];
for (k = 0; k < i; k++) {
U[i][j] = U[i][j] - ((L[i][k] * U[k][j]) / L[i][i]);
}
}
}
}
// 输出L和U矩阵
printf("L矩阵为:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%f ", L[i][j]);
}
printf("\n");
}
printf("U矩阵为:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%f ", U[i][j]);
}
printf("\n");
}
// 释放内存
for (i = 0; i < n; i++) {
free(A[i]);
free(L[i]);
free(U[i]);
}
free(A);
free(L);
free(U);
return 0;
}
```
运行程序后,输入矩阵的阶数和矩阵的系数,即可得到经过Crout分解后的L和U矩阵。
阅读全文