1.函数
行列式的值等于其第一行各元素乘以各自对应的代数余子式之积的和。
(注:本代码仅提供一种思路,并不代表最优解)
1/// <summary> 2/// 递归计算行列式的值 3/// </summary> 4/// <param name="matrix">矩阵</param> 5/// <returns></returns> 6public static double Determinant(double[][] matrix) 7{ 8 //二阶及以下行列式直接计算 9 if (matrix.Length == 0) return 0; 10 else if (matrix.Length == 1) return matrix[0][0]; 11 else if (matrix.Length == 2) 12 { 13 return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]; 14 } 15 16 //对第一行使用“加边法”递归计算行列式的值 17 double dSum = 0, dSign = 1; 18 for (int i = 0; i < matrix.Length; i++) 19 { 20 double[][] matrixTemp = new double[matrix.Length - 1][]; 21 for (int count = 0; count < matrix.Length - 1; count++) 22 { 23 matrixTemp[count] = new double[matrix.Length - 1]; 24 } 25 26 for (int j = 0; j < matrixTemp.Length; j++) 27 { 28 for (int k = 0; k < matrixTemp.Length; k++) 29 { 30 matrixTemp[j][k] = matrix[j + 1][k >= i ? k + 1 : k]; 31 } 32 } 33 34 dSum += (matrix[0][i] * dSign * Determinant(matrixTemp)); 35 dSign = dSign * -1; 36 } 37 38 return dSum; 39}
2.Main函数调用
1static void Main(string[] args) 2{ 3 //二阶行列式 -2 4 double[][] matrix1 = new double[][] 5 { 6 new double[] { 1, 2 }, 7 new double[] { 3, 4 } 8 }; 9 Console.WriteLine(Determinant(matrix1)); 10 11 //三阶行列式 -4 12 double[][] matrix2 = new double[][] 13 { 14 new double[] { 2, 0, 1 }, 15 new double[] { 1, -4, -1 }, 16 new double[] { -1, 8, 3 } 17 }; 18 Console.WriteLine(Determinant(matrix2)); 19 20 //四阶行列式 -21 21 double[][] matrix3 = new double[][] 22 { 23 new double[] { 1, 2, 0, 1 }, 24 new double[] { 1, 3, 5, 0 }, 25 new double[] { 0, 1, 5, 6 }, 26 new double[] { 1, 2, 3, 4 } 27 }; 28 Console.WriteLine(Determinant(matrix3)); 29 Console.ReadLine(); 30}
3.运行结果
