废话少说,直接上干货。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MaxSize 100
double A[MaxSize][MaxSize]; //系数矩阵
double B[MaxSize]; //系数矩阵
double C[MaxSize][MaxSize]; //去对角线矩阵
double D[MaxSize][MaxSize]; //储存D逆
double E[MaxSize][MaxSize]; //储存-(D-1)*(L+U)
double F[MaxSize]; //(D-1)*B
double X[MaxSize];
double X1[MaxSize];
double Y[MaxSize];
#define e 1e-6 //10的负6次方
int n; //矩阵尺寸大小
// 初始化矩阵
void InitMatrix()
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (i == j)
D[i][j] = A[i][j];
else
C[i][j] = A[i][j];
}
}
}
// 雅可比迭代求解线性方程组
int Jacobi()
{
int k;
double sum, max_diff;
for (k = 0; ; k++)
{
max_diff = 0.0;
for (int i = 0; i < n; i++)
{
sum = 0.0;
for (int j = 0; j < n; j++)
{
if (j != i)
sum += A[i][j] * X[j];
}
X1[i] = (B[i] - sum) / A[i][i];
double diff = fabs(X1[i] - X[i]);
if (diff > max_diff)
max_diff = diff;
}
for (int i = 0; i < n; i++)
X[i] = X1[i];
if (max_diff < e) // 满足精度要求退出循环
break;
}
return k; // 返回迭代次数
}
// 输入系数矩阵和向量
void input()
{
int i, j;
printf("请输入系数矩阵A:\n");
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf_s("%lf", &A[i][j]);
printf("请输入向量B:\n");
for (i = 0; i < n; i++)
scanf_s("%lf", &B[i]);
printf("请输入初始向量X:\n");
for (i = 0; i < n; i++)
scanf_s("%lf", &X[i]);
}
// 打印方程组的近似解
void print()
{
int i;
printf("方程组的近似解:\n");
for (i = 0; i < n; i++)
printf("%lf\n", X[i]);
}
int main()
{
printf("请输入矩阵行数:\n");
scanf_s("%d", &n);
printf("\n");
input();
InitMatrix();
int N =Jacobi();
print();
printf("迭代次数为:%d",N);
return 0;
}