gpt4 book ai didi

c - 在 C 中求矩阵的行列式

转载 作者:行者123 更新时间:2023-11-30 17:37:30 25 4
gpt4 key购买 nike

这是矩阵行列式的C代码,但它给出了编译错误。

代码是:

#include<stdio.h>
#include<math.h>
int m;

float determinant(float b[][]);

int main(void)
{
int i,j,m;
printf("enter a no: ");
scanf("%d",&m);
//printf("%d",m);
float arr[m][m];
for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
scanf("%f",&arr[i][j]);
//printf("%f",arr[i][j]);
}
}


for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
printf("%f ",arr[i][j]);
}

printf("\n");
}



float det = determinant(arr);

printf("Determinant= %f ", det);




}

float determinant(float b[][])
{
int i,j;
int p;
float sum = 0;
float c[m][m];

for(i=0;i<m;i++)
{
for(j=0;j<m;j++)
{
printf("%f ",b[i][j]);
}

printf("\n");
}



if(m==2)
{
printf("Determinant for m=2");
sum = b[0][0]*b[1][1] - b[0][1]*b[1][0];
return sum;
}

for(p=0;p<m;p++)
{
int h = 0,k = 0;
for(i=1;i<m;i++)
{
for( j=0;j<m;j++)
{
if(j==p)
continue;
c[h][k] = b[i][j];
k++;
if(k == m-1)
{
h++;
k = 0;
}
}
}

m=m-1;
sum = sum + b[0][p]*pow(-1,p) * determinant(c);

}




return sum;
}

编译错误是:

det.c:5:25: error: array type has incomplete element type
det.c: In function ‘main’:
det.c:36:2: error: type of formal parameter 1 is incomplete
det.c: At top level:
det.c:45:25: error: array type has incomplete element type
det.c: In function ‘determinant’:
det.c:91:3: error: type of formal parameter 1 is incomplete
det.c:99: confused by earlier errors, bailing out
Preprocessed source stored into /tmp/cc1Kp9KD.out file, please attach this to your bug report.

我认为错误在于二维数组的传递。当我将它作为指针传递时,它会发出警告,但没有错误,但它不会给出正确的结果,因为总是给出行列式为零。所以我猜数组不仅仅被传递,当我在函数行列式中打印它时,它也不会打印。请帮助我,因为我的项目因此陷入困境。

最佳答案

在您的代码中,

scanf("%d",&m);
//printf("%d",m);
float arr[m][m];

这里 arr 是一个具有静态内存分配的二维数组,因此您不能在运行时读取 m 并像这样声明 arr。
因此,如果您想动态定义数组,请使用动态内存分配方法,例如 C 中的 malloc()

关于c - 在 C 中求矩阵的行列式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22385001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com