当我试图计算一个矩阵的三阶行列式时,我收到了错误的输出。在二阶的时候,效果很好。更具体地说,我没有收到9个值(v[1,1],v[1,2]等),而是收到了更多。我认为数组有问题,但是idk。。
代码:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
void main(void) {
int i,j,n,i_max,j_max,ordin,i_m,j_m;
long int det;
int v[3][3];
int e[3];
int nr=0;
printf("\nIntroduceti ordinul matricei:\t");
scanf("%d",&n);
if (n==2) {
i_max=n;
j_max=n;
printf("\nIntroduceti valorile matricei:\n");
for (i=1;i<=i_max;i++) {
for (j=1;j<=j_max;j++) {
printf("v[%d,%d]= ",i,j);
scanf("%d",&(v[i][j]));
nr++;
e[nr] = v[i][j];
}
}
det = (e[1]*e[4])-(e[2]*e[3]);
printf("\nDeterminantul matricei este: %ld\n",det);
if (det != 0)
printf("Matricea de ordinul %d este inversabila !",n);
else printf("Matricea de ordinul %d nu este inversabila!",n);
} else if (n==3) {
i_m=n;
j_m=n;
printf("\nIntroduceti valorile matricei:\n");
for (i=1; i<= i_m; i++) {
for (j=1; j<= j_m; j++) {
printf("v[%d,%d]= ",i,j);
scanf("%d",&(v[i][j]));
nr++;
e[nr] = v[i][j];
}
}
det = (e[1]*e[5]*e[9])+(e[2]*e[6]*e[7])+(e[3]*e[4]*e[8])-(e[3]*e[5]*e[7])-(e[2]*e[4]*e[9])-(e[1]*e[6]*e[8]);
printf("Determinantul matricei este: %ld\n",det);
if (det != 0)
printf("Matricea de ordinul %d este inversabila!",n);
else
printf("Matricea de ordinul %d nu este inversabila!",n);
} else
printf("Ordinul matricei este incorect!");
return 0;
}
最佳答案
首先,你声明
int v[3][3];
int e[3];
对于
e
没有足够的项,因为您将其用于具有3 x 3=9个元素的v
。因此,似乎可以通过将第二个语句改为
int e[9];
但这并不是故事的结尾。
在
for
循环中,您循环也不是从0
循环(这在C语言中很常见),而是从1
循环,因此您需要为所有数组增加1个索引!所以宣布
int v[4][4]; /* for using indices from 1 to 3 */
int e[10]; /* for using indices from 1 to 9 */