在运行此程序期间,我遇到了分段错误。我试图解决一个线性方程,从.dat文件接收数字。我可以在高斯函数之前到达该部分,但之后它会转储。有帮助吗?谢谢。
void prob2(void)
{
FILE *matrix;
matrix=fopen("matrix.dat", "r");
double a1, a2, a3, a4, **A, *a, *rhs, length;
int k, row;
A=(double **)malloc(4*sizeof(double *));
printf("\n");
for(k=1;k<=4; k++)
{
a=(double *)malloc(4*sizeof(double));
fscanf(matrix, "%lf %lf %lf %lf", &a1, &a2, &a3, &a4);
a[0]=a1;
a[1]=a2;
a[2]=a3;
a[3]=a4;
printf(" a[%d][] = %5.2f %5.2f %5.2f %5.2f\n", k, a[0], a[1], a[2], a[3]);
}
rhs=(double *)malloc(4*sizeof(double));
fscanf(matrix, "%lf %lf %lf %lf", &a1, &a2, &a3, &a4);
rhs[0]=a1;
rhs[1]=a2;
rhs[2]=a3;
rhs[3]=a4;
printf("\nb[]={ %.3f, %.3f, %.3f, %.3f }\n", rhs[0],rhs[1],rhs[2],rhs[3]);
printf("hiii");
gauss(4, A, rhs);
/* print the solution x[] stored in rhs[]:*/
printf("x[]={%7.3f, %7.3f, %7.3f, %7.3f }\n",
rhs[0], rhs[1], rhs[2], rhs[3]);
length=sqrt(pow(rhs[0],2)+pow(rhs[1],2)+pow(rhs[2],2)+pow(rhs[3],2));
printf("The length of x[] is %.6lf", length);
/* free memory */
for(row=0; row<4; row++) free(A[row]);
free(A);
free(rhs);
fclose(matrix);
}
void gauss(int n, double **A, double *rhs)
{
/* By Gauss elimination, solve a system of equations:
A[][]*x[] = rhs[] where A[][] (n x n)
and rhs[] (n x 1) are input */
/* x[] is stored in rhs[] */
printf("hiii");
double one = 1.0, zero=0.0;
double b, c, d;
int nm, row, col, krow;
nm = n - 1;
if(n == 1)
{
rhs[0] /= A[0][0]; A[0][0] = one;
return;
}
/* forward reduction */
for(row=0; row<nm; row++)
{
b = A[row][row]; A[row][row] = one;
for(col=row+1; col<n; col++) A[row][col] /= b;
rhs[row] /= b;
/* sweep rows of A[row+1][] to A[nm][] */
for(krow=row+1; krow<n; krow++)
{
c = A[krow][row]; A[krow][row] = zero;
for(col=row+1; col<n; col++) A[krow][col] -= c * A[row][col];
rhs[krow] -= c * rhs[row];
}
}
/* back substitution */
rhs[nm] /=A[nm][nm];
for(row=nm-1; row>=0; row--)
{
for(col=row+1; col<n; col++) rhs[row] -= A[row][col]*rhs[col];
}
return;
}
答案 0 :(得分:2)
看起来未分配矩阵A
。我认为在分配a
之后你需要这个:
A[k-1] = a;
答案 1 :(得分:0)
当算法遇到对角线上的0时,通常会发生这种情况。您需要使用旋转来避免这种情况。有关详细信息,请参阅高斯消除的Wikipedia article。
答案 2 :(得分:0)
你永远不会在A中存储任何东西。你在k = 1 ... 4循环中使用malloc,但你永远不会保存你的malloc。