输入方程组,用三角分解法解决c语言
时间: 2024-02-23 13:58:21 浏览: 121
C语言crout分解法.rar_C语言crout分解法_choicev4m
5星 · 资源好评率100%
以下是使用三角分解法解决线性方程组的C语言代码:
```c
#include <stdio.h>
void crout(double **a, int n, double *b) {
int i, j, k;
double sum;
double *c, *d;
c = (double *)malloc(n * sizeof(double));
d = (double *)malloc(n * sizeof(double));
for (i = 0; i < n; i++) {
d[i] = a[i][i];
for (j = 0; j < i; j++) {
sum = 0.0;
for (k = 0; k < j; k++) {
sum += a[i][k] * c[k] * d[j];
}
a[i][j] = (a[i][j] - sum) / d[j];
}
sum = 0.0;
for (k = 0; k < i; k++) {
sum += a[i][k] * c[k];
}
c[i] = b[i] - sum;
}
for (i = 0; i < n; i++) {
for (j = 0; j < i; j++) {
sum = 0.0;
for (k = 0; k < j; k++) {
sum += a[j][k] * a[i][k] * d[k];
}
a[j][i] = (a[j][i] - sum) / d[j];
}
}
for (i = 0; i < n; i++) {
sum = 0.0;
for (k = 0; k < i; k++) {
sum += a[i][k] * d[k] * c[k];
}
c[i] = (c[i] - sum) / d[i];
}
for (i = n - 1; i >= 0; i--) {
sum = 0.0;
for (k = i + 1; k < n; k++) {
sum += a[i][k] * b[k];
}
b[i] = (c[i] - sum) / a[i][i];
}
free(c);
free(d);
}
int main() {
int n, i, j;
double **a, *b;
printf("Enter the number of equations: ");
scanf("%d", &n);
a = (double **)malloc(n * sizeof(double *));
for (i = 0; i < n; i++) {
a[i] = (double *)malloc(n * sizeof(double));
}
b = (double *)malloc(n * sizeof(double));
printf("Enter the coefficients of the equations:\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%lf", &a[i][j]);
}
}
printf("Enter the constants of the equations:\n");
for (i = 0; i < n; i++) {
scanf("%lf", &b[i]);
}
crout(a, n, b);
printf("\nThe solution is:\n");
for (i = 0; i < n; i++) {
printf("x[%d] = %lf\n", i, b[i]);
}
for (i = 0; i < n; i++) {
free(a[i]);
}
free(a);
free(b);
return 0;
}
```
该代码使用了Crout方法进行三角分解,并用前、后代替法求解方程组的解。在运行代码之前,需要输入方程组的系数和常数。
阅读全文