矩阵行列式的计算误差是多少



我正试图找到4x4矩阵的行列式,它被编译,获取矩阵的值,然后突然终止,显示出一些未知错误,导致它停止工作。

#include <stdio.h>
int detcalfnl(int a,int b,int c,int d)
{
int anss;
anss = ((a*d)-(b*c));
return anss;
}
/*********************************************************************************************************************************************************/
void detcalthree(int mat[3][3],int *ansss)
{
*ansss=0;
int x;
for(x=0;x<3;x++)
{
if(x==0)
{
*ansss+=((mat[0][x])*(detcalfnl(mat[x+1][x+1],mat[x+1][x+2],mat[x+2][x+1],mat[x+2][x+2])));
}
else if(x==1)
{
*ansss+=((-1)*((mat[0][x])*(detcalfnl(mat[x][x-1],mat[x][x+1],mat[x+1][x-1],mat[x+1][x+1]))));
}
else if(x==2)
{
*ansss+=((mat[0][x])*(detcalfnl(mat[x-1][x-2],mat[x-1][x-1],mat[x][x-2],mat[x][x-1])));
}
}
}
/*********************************************************************************************************************************************************/
void detcalfour(int mat[4][4],int *ansss)
{
*ansss=0;
int a1[3][3],a2[3][3],a3[3][3],a4[3][3];
int x,row,clm,a5,a6,a7,a8;
int *p5=&a5;
int *p6=&a6;
int *p7=&a7;
int *p8=&a8;
for(x=0;x<4;x++)
{
int a=0;
int b=0;
for(row=1;row<4;row++)
{
for(clm=0;clm<4;clm++)
{
if(clm==x){continue;}
else
{
if(x==0)
{
a1[b][a]=mat[row][clm];
}
else if(x==1)
{
a2[b][a]=mat[row][clm];
}
else if(x==2)
{
a3[b][a]=mat[row][clm];
}
else if(x==3)
{
a4[b][a]=mat[row][clm];
}
}
a++;
}
b++;
}
}
detcalthree(a1,p5);
detcalthree(a2,p6);
detcalthree(a3,p7);
detcalthree(a4,p8);
*ansss=((mat[0][0])*(*p5))-((mat[0][1])*(*p6))+((mat[0][2])*(*p7))-((mat[0][3])*(*p8));
}
/*********************************************************************************************************************************************************/
int main()
{
int dim,row,clm,fnlans;
printf("Please Enter The Dimension Of Matrix :");
scanf("%d",&dim);
printf("nnn");
int oprnd[dim][dim];
for(row=0;row<dim;row++)
{
for(clm=0;clm<dim;clm++)
{
printf("nPlease Provide Element For Row %d and Column %d : ",row+1,clm+1);
scanf("%d",&oprnd[row][clm]);
}
}
int *pfs=&fnlans;
detcalfour(oprnd,pfs);
printf("nnnValue Of Determinant Is %d nn",*pfs);
return 0;
}

detcal4中,在x上的循环内,ab设置为零,a在内部循环内(在clm上(使用a++递增。即使在外部循环迭代时,这种递增也会重复;CCD_ 8从不复位为零。因此,它增加到数组维度之外。这导致访问数组a1a2a3a4的代码越界,损坏内存。

每次启动clm上的循环时,将a重置为零。将int a=0;row上的循环外部移动到循环内部。

作为一种良好的一般做法,在需要变量的地方声明变量。由于在row的循环之外不需要a,因此不应在该循环之外声明它,并且在内部声明它会自动避免此错误。

最新更新