jacobi迭代法c语言代码飞花舞者
时间: 2023-08-12 10:07:56 浏览: 20
下面是使用 Jacobi 迭代法求解线性方程组的 C 语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_ITER 1000
#define TOL 1e-6
int main()
{
int n;
printf("Enter the size of the matrix: ");
scanf("%d", &n);
double **A = (double **) malloc(n * sizeof(double *));
for (int i = 0; i < n; i++) {
A[i] = (double *) malloc(n * sizeof(double));
}
double *b = (double *) malloc(n * sizeof(double));
double *x = (double *) malloc(n * sizeof(double));
double *x_new = (double *) malloc(n * sizeof(double));
printf("Enter the matrix coefficients:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%lf", &A[i][j]);
}
}
printf("Enter the right-hand side vector:\n");
for (int i = 0; i < n; i++) {
scanf("%lf", &b[i]);
}
int iter = 0;
double error = 1;
while (iter < MAX_ITER && error > TOL) {
for (int i = 0; i < n; i++) {
x_new[i] = b[i];
for (int j = 0; j < n; j++) {
if (i != j) {
x_new[i] -= A[i][j] * x[j];
}
}
x_new[i] /= A[i][i];
}
error = 0;
for (int i = 0; i < n; i++) {
error += fabs(x_new[i] - x[i]);
x[i] = x_new[i];
}
iter++;
}
if (iter < MAX_ITER) {
printf("Solution:\n");
for (int i = 0; i < n; i++) {
printf("x[%d] = %lf\n", i, x[i]);
}
} else {
printf("Maximum number of iterations exceeded.\n");
}
free(x_new);
free(x);
free(b);
for (int i = 0; i < n; i++) {
free(A[i]);
}
free(A);
return 0;
}
```
希望能够帮到你!
相关推荐















