0

嗯,这让我很头疼。我正在构建一个矩阵行列式函数来计算 NxN 行列式,并且我正在使用递归。逻辑工作正常,但我无法正确计算最终值。

这是我的矩阵行列式代码:

 public static double determinant(double[,]array){
            double det=0;
            double total = 0;
            double[,] tempArr = new double[array.GetLength(0) - 1, array.GetLength(1) - 1];

            if(array.GetLength(0)==2)
            {
                det = array[0, 0] * array[1, 1] - array[0, 1] * array[1, 0];
            }

            else { 

                for (int i = 0; i <1; i++)
                {
                    for (int j = 0; j < array.GetLength(1); j++)
                    {
                        if (j % 2 != 0) array[i, j] = array[i, j] * -1;
                       tempArr= fillNewArr(array, i, j);
                       det+=determinant(tempArr);
                       total =total + (det * array[i, j]);
                    }
                }
                 }
            return det;
        }

而关于fillNewArr方法,它只是一种修剪数组的方法,方法如下:p

ublic static double[,] fillNewArr(double[,] originalArr, int row, int col)
        {
            double[,] tempArray = new double[originalArr.GetLength(0) - 1, originalArr.GetLength(1) - 1];

            for (int i = 0, newRow = 0; i < originalArr.GetLength(0); i++)
            {
                if (i == row)
                    continue;
                for (int j = 0, newCol=0; j < originalArr.GetLength(1); j++)
                {
                    if ( j == col) continue;
                    tempArray[newRow, newCol] = originalArr[i, j];

                    newCol++;
                }
                newRow++;
            }
            return tempArray;

        }

该方法按“我假设”的方式工作,但最终结果没有以正确的方式计算,为什么会这样?!

4x4 阵列示例:

{2 6 6 2}
{2 7 3 6}
{1 5 0 1}
{3 7 0 7}

最终结果应该是-168,而我的是104!

4

1 回答 1

1

这一点

if (j % 2 != 0) array[i, j] = array[i, j] * -1;
tempArr= fillNewArr(array, i, j);
det+=determinant(tempArr);
total =total + (det * array[i, j]);

total使用一个不再使用的变量。它可能应该是这样的

double subdet = determinant(fillNewArr(array, i, j));
if (j % 2 != 0) subdet *= -1;
det += array[i, j] * subdet;   
于 2014-10-10T23:26:41.903 回答