计算 C++ 中的行列式
我试图计算 3 * 3 矩阵(或更多)的行列式,矩阵值范围从 (-1, 到 1)。然而,当我计算行列式时,我得到的结果是0。
[...]
srand(time(NULL));
//Random generation of values between -1 and 1
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
temp = (rand() % (500)) + 0;
temp = temp/250;
array[i][j] = (temp - 1);
}
[...]
double array2[10][10];
double detrm = 0;
int s = 1;
int i, j, m, n, c;
for (c = 0; c < x; c++)
{
m = 0;
n = 0;
for (i = 0; i < x; i++)
{
for (j = 0; j < x; j++)
{
array2[i][j] = 0;
if (i != 0 && j != c)
{
array2[m][n] = a[i][j];
if ( n < (x - 2))
{
n++;
}
else
{
n = 0;
m++;
}
}
}
}
detrm = detrm + (s*a[0][c]*determinant(array2, (x - 1)));
s = -1*s;
}
return(detrm);
I was trying to calculate the determinant of a 3 * 3 matrix (or more) with the matrix values ranging from (-1, to 1). However, I get a result of 0 when I calculate the determinant.
[...]
srand(time(NULL));
//Random generation of values between -1 and 1
for(i = 0; i < 3; i++)
{
for(j = 0; j < 3; j++)
{
temp = (rand() % (500)) + 0;
temp = temp/250;
array[i][j] = (temp - 1);
}
[...]
double array2[10][10];
double detrm = 0;
int s = 1;
int i, j, m, n, c;
for (c = 0; c < x; c++)
{
m = 0;
n = 0;
for (i = 0; i < x; i++)
{
for (j = 0; j < x; j++)
{
array2[i][j] = 0;
if (i != 0 && j != c)
{
array2[m][n] = a[i][j];
if ( n < (x - 2))
{
n++;
}
else
{
n = 0;
m++;
}
}
}
}
detrm = detrm + (s*a[0][c]*determinant(array2, (x - 1)));
s = -1*s;
}
return(detrm);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能会有所帮助 - 请参阅代码中的注释以获取解释:
This may Help - see comments within the code for an explanation:
您有一种更新
m
和n
的粗暴方法。您应该在外循环中对i
递增m
,并在外循环中初始化n
并在内循环中递增它。我认为你的代码会像你编写的那样工作,但我认为你的条件应该是i
i
i
i
i
i
i
i
i
i
i n-1
而不是i
n-2
。但我建议不要更改最少数量的字符来使代码正常工作,而是重新调整增量,以免出现问题。You have a crufty way of updating
m
andn
. You should incrementm
in the outer loop overi
, and initializen
within the outer loop and increment it within the inner loop. I think that your code would work as you wrote it, but I think that your conditional should have beeni < n-1
instead ofi < n-2
. But instead of changing the fewest number of characters to get the code to work, I recommend restructuring the increments so that the issue doesn't arise.