Дана квадратная матрица размерности n*n вычислить ее определитель - C#
Формулировка задачи:
Дана квадратная матрица размерности n*n вычислить ее определитель.
Нужна помощь в написании кода, за ранее спасибо
Решение задачи: «Дана квадратная матрица размерности n*n вычислить ее определитель»
textual
Листинг программы
using System;
using System.Linq;
using System.Text;
namespace ConsoleApplication
{
class Program
{
public class Matrix
{
public float[,] matrix = null;
public int CountColumn { get; private set; }
public int CountRow { get; private set; }
public Matrix(int x = 1, int y = 1)
{
matrix = new float[x, y];
CountColumn = y;
CountRow = x;
}
public float this[int x, int y]
{
get { return matrix[x, y]; }
set { matrix[x, y] = value; }
}
public float[] GetRow(int row)
{
if (row >= CountRow) throw new IndexOutOfRangeException("Индекс строки не принадлежит массиву.");
float[] ret = new float[CountColumn];
for (int i = 0; i < CountColumn; i++)
ret[i] = matrix[row, i];
return ret;
}
public void SetRow(float[] values, int row)
{
if (row >= CountRow) throw new IndexOutOfRangeException("Индекс строки не принадлежит массиву.");
for (int i = 0; i < (CountColumn > values.Length ? values.Length : CountColumn); i++)
matrix[row, i] = values[i];
}
public float Determinant()
{
if (CountColumn != CountRow) throw new ArgumentException("Вычисление определителя возможно только для квадратных матриц.");
Matrix _matrix = new Matrix(CountRow, CountColumn);
_matrix.matrix = (float[,])this.matrix.Clone();
float det = 1;
int order = CountRow;
for (int i = 0; i < order - 1; i++)
{
float[] masterRow = _matrix.GetRow(i);
det *= masterRow[i];
if (det == 0) return 0;
for (int t = i + 1; t < order; t++)
{
float[] slaveRow = _matrix.GetRow(t);
float[] tmp = MulArrayConst(masterRow, slaveRow[i] / masterRow[i]);
float[] source = _matrix.GetRow(t);
_matrix.SetRow(SubArray(source, tmp), t);
}
}
det *= _matrix[order - 1, order - 1];
return det;
}
public override string ToString()
{
StringBuilder ret = new StringBuilder();
if (matrix == null) return ret.ToString();
for (int i = 0; i < CountRow; i++)
{
for (int t = 0; t < CountColumn; t++)
{
ret.Append(matrix[i, t]);
ret.Append("\t");
}
ret.Append("\n");
}
return ret.ToString();
}
float[] SubArray(float[] A, float[] B)
{
float[] ret = (float[])A.Clone();
for (int i = 0; i < (A.Length > B.Length ? A.Length : B.Length); i++)
ret[i] -= B[i];
return ret;
}
float[] MulArrayConst(float[] array, float number)
{
float[] ret = (float[])array.Clone();
for (int i = 0; i < ret.Length; i++)
ret[i] *= number;
return ret;
}
void generator(int x, int y, int startGen)
{
matrix = new float[x, y];
Random rnd = new Random(startGen);
for (int i = 0; i < x * y; i++)
{
int X = i / y;
int Y = i - y * X;
matrix[X, Y] = rnd.Next(-10, 10);
}
}
}
static void Main()
{
Matrix m1 = new Matrix(3, 3);
Console.WriteLine(m1.Determinant());
}
}
}