В данную программу добавить код чтоб считался определитель квадратной матрицы - C#
Формулировка задачи:
Console.Write("Введите размер квадратной матрицы ");
int n = Convert.ToInt32(Console.ReadLine());
while (n <= 0)
{
Console.WriteLine("неверный размер!");
n = Convert.ToInt32(Console.ReadLine());
}
int[,] a = new int[n, n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
Console.WriteLine("Введите {0}-ую строку, {1}-й элемент", i + 1, j + 1);
a[i, j] = Convert.ToInt32(Console.ReadLine());
}
}
Console.WriteLine();
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < n; j++)
{
Console.Write(a[i, j] + "\t");
}
Console.WriteLine();
}
Console.ReadLine();Решение задачи: «В данную программу добавить код чтоб считался определитель квадратной матрицы»
textual
Листинг программы
if (a.GetLength(0) != a.GetLength(1)) throw new Exception(" Число строк в матрице не совпадает с числом столбцов");
double det = 0;
int Rank = a.GetLength(0);
if (Rank == 1) det = a[0, 0];
if (Rank == 2) det = a[0, 0] * a[1, 1] - a[0, 1] * a[1, 0];
if (Rank > 2)
{
for (int j = 0; j < a.GetLength(1); j++)
{
det += Math.Pow(-1,0+j)*a[0, j] * Determ(GetMinor(a, 0, j));
}
}
//Вот такой метод нужно добавить в класс
public static double[,] GetMinor(int[,] matrix, int row, int column)
{
if (matrix.GetLength(0) != matrix.GetLength(1)) throw new Exception(" Число строк в матрице не совпадает с числом столбцов");
int[,] buf = new int[matrix.GetLength(0)-1,matrix.GetLength(0)-1];
for (int i=0;i<matrix.GetLength(0);i++)
for (int j=0;j<matrix.GetLength(1);j++)
{
if ((i!=row) || (j!=column))
{
if (i > row && j < column) buf[i - 1, j] = matrix[i, j];
if (i < row && j > column) buf[i, j - 1] = matrix[i, j];
if (i > row && j > column) buf[i - 1, j - 1] = matrix[i,j];
if (i < row && j < column) buf[i, j] = matrix[i, j];
}
}
return buf;
}