C\#가 변 법 으로 행렬식 의 값 을 계산 합 니 다.

본 논문 의 사례 는 C\#가 변 법 으로 행렬식 의 값 을 계산 하 는 것 을 서술 하 였 다.모두 에 게 참고 하도록 공유 하 다.구체 적 으로 다음 과 같다.
1.함수
행렬식 의 값 은 첫 번 째 줄 의 각 요소 에 각자 대응 하 는 대수 여 자 식 의 적 을 곱 한 것 과 같다.
(비고:이 코드 는 하나의 사고방식 만 제공 할 뿐 최 우 해 를 대표 하지 않 습 니 다)

/// <summary>
///          
/// </summary>
/// <param name="matrix">  </param>
/// <returns></returns>
public static double Determinant(double[][] matrix)
{
  //            
  if (matrix.Length == 0) return 0;
  else if (matrix.Length == 1) return matrix[0][0];
  else if (matrix.Length == 2)
  {
    return matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0];
  }
  //      “   ”         
  double dSum = 0, dSign = 1;
  for (int i = 0; i < matrix.Length; i++)
  {
    double[][] matrixTemp = new double[matrix.Length - 1][];
    for (int count = 0; count < matrix.Length - 1; count++)
    {
      matrixTemp[count] = new double[matrix.Length - 1];
    }
    for (int j = 0; j < matrixTemp.Length; j++)
    {
      for (int k = 0; k < matrixTemp.Length; k++)
      {
        matrixTemp[j][k] = matrix[j + 1][k >= i ? k + 1 : k];
      }
    }
    dSum += (matrix[0][i] * dSign * Determinant(matrixTemp));
    dSign = dSign * -1;
  }
  return dSum;
}

2.Main 함수 호출

static void Main(string[] args)
{
  //      -2
  double[][] matrix1 = new double[][]
  {
    new double[] { 1, 2 },
    new double[] { 3, 4 }
  };
  Console.WriteLine(Determinant(matrix1));
  //      -4
  double[][] matrix2 = new double[][]
  {
    new double[] { 2, 0, 1 },
    new double[] { 1, -4, -1 },
    new double[] { -1, 8, 3 }
  };
  Console.WriteLine(Determinant(matrix2));
  //      -21
  double[][] matrix3 = new double[][]
  {
    new double[] { 1, 2, 0, 1 },
    new double[] { 1, 3, 5, 0 },
    new double[] { 0, 1, 5, 6 },
    new double[] { 1, 2, 3, 4 }
  };
  Console.WriteLine(Determinant(matrix3));
  Console.ReadLine();
}

3.실행 결과

본 고 에서 말 한 것 이 여러분 의 C\#프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기