雅克比迭代出现.exe停止工作
#include<stdio.h>#include<math.h>
#define N 6
void Jacobi(float a[][6], float b[], int n, float x0[], float delta, int maxn)//雅克比迭代法
{
int k, i, j;
float sum=0, err=0, x1[6]={0,0,0,0,0,0};
for (k = 0; k < maxn; k++)
{
for (i = 0; i<n; i++)
{
for (j = 0; j<i; i++)
sum += a[i][j] * x0[j];
for (j = i + 1; j<n; j++)
sum += a[i][j] * x0[j];
x1[i] = (b[i] - sum) / a[i][i];
err += (x1[i] - x0[i])*(x1[i] - x0[i]);
sum = 0;
}
for(i=0;i<N;i++)
x0[i]=x1[i];
err = sqrt(err);
if (err < delta)
break;
}
if (k >= maxn-1)
printf("此次迭代发散,结果作废");
else
{
printf("经过%d次雅克比迭代得到以下解向量\n", k+1);
for (i = 0; i<N; i++)
printf("%3.4f", x0[i]);
}
}
void GaussSeidel(float a[][6], float b[], int n, float x0[], float delta, int maxn)//高斯-赛德尔迭代
{
int k, i, j;
float sum=0, err=0, Temporary=0;
for (k = 1; k <= maxn; k++)
{
for (i = 0; i<n; i++)
{
for (j = 0; j<i; i++)
{
sum += a[i][j] * x0[j];
}
for (j = i + 1; j<n; j++)
{
sum += a[i][j] * x0[j];
}
Temporary = (b[i] - sum) / a[i][i];
err += (Temporary - x0[i])*(Temporary - x0[i]);
x0[i] = Temporary;
sum = 0;
}
err = sqrt(err);
if (err < delta)
break;
}
if (k == maxn)
printf("此次迭代发散,结果作废");
else
{
printf("经过%d次高斯-赛德尔迭代得到以下解向量\n", k);
for (i = 0; i<N; i++)
printf("%3.4f", x0[i]);
}
}
void main()
{
float A[N][N], x0[N]={0,0,0,0,0,0}, b[N], delta=0.0001;
int i, j, k,maxn, n=6;
FILE *fp=fopen("inA.txt","r"),*fq=fopen("inb.txt","r");
if(!fp)
{
printf("file inA.txt can't open\n");
}
if(!fq)
{
printf("file inb.txt can't open\n");
}
while(!feof(fp))
{
for (i = 0; i < N; i++)
for (j = 0; j < N; j++)
fscanf(fp,"%f", &A[i][j]);
printf("读入的A矩阵如下:\n");
for (i = 0; i < N; i++)
{
for (j = 0; j < N; j++)
printf("%8.1f", A[i][j]);
printf("\n");
}
printf("\n\n");
}
while(!feof(fq))
{
for(i=0;i<N;i++)
fscanf(fq,"%f", &b[i]);
printf("读入的b系数矩阵如下:\n");
for (i = 0; i < N; i++)
printf("%8.1f", b[i]);
printf("\n");
}
printf("请输入迭代最大次数\n");
scanf("%d", &maxn);
printf("请选择算法:\n1.雅克比迭代\n2.高斯赛德尔迭代\n");
scanf("%d",&k);
if(k==1)
Jacobi(A, b, n, x0, delta, maxn);//调用雅克比迭代法
else
GaussSeidel(A, b, n, x0, delta, maxn);//调用高斯赛德尔迭代法
}