Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Runtime.InteropServices;
- class HelloWorld
- {
- static void Main()
- {
- int n;
- Console.Write("Введiть розмiрнiсть матрицi: ");
- n = int.Parse(Console.ReadLine());
- int[,] matrix = new int[n, n];
- Console.WriteLine("1) Випадково згенерувати матрицю\n2) Ввести матрицю вручну");
- int choise = int.Parse(Console.ReadLine());
- int i, j;
- switch (choise)
- {
- case 1:
- {
- Random r = new Random();
- for (i = 0; i < matrix.GetLength(0); i++)
- {
- for (j = 0; j < matrix.GetLength(1); j++)
- {
- matrix[i, j] = r.Next(0, 99);
- }
- }
- break;
- }
- case 2:
- {
- for (i = 0; i < matrix.GetLength(0); i++)
- {
- for (j = 0; j < matrix.GetLength(1); j++)
- {
- Console.Write($"Введiть Matrix{i + 1}{j + 1}: ");
- matrix[i, j] = int.Parse(Console.ReadLine());
- }
- }
- break;
- }
- default:
- {
- Console.WriteLine("Error");
- Environment.Exit(1);
- break;
- }
- }
- Console.WriteLine("\nВведена матриця:");
- for (i = 0; i < matrix.GetLength(0); i++)
- {
- for (j = 0; j < matrix.GetLength(0); j++)
- {
- Console.Write($"{matrix[i, j]:D2} ");
- }
- Console.WriteLine();
- }
- //finding determinant
- double determinant = CalculateDeterminant(matrix);
- Console.WriteLine($"Визначник матрицi: {determinant}");
- }
- static int CalculateDeterminant(int[,] matrix)
- {
- int det = 0;
- int[,] submatrix = new int[matrix.GetLength(0) - 1, matrix.GetLength(0) - 1];
- if (matrix.GetLength(0) == 2)
- {
- return ((matrix[0, 0] * matrix[1, 1]) - (matrix[1, 0] * matrix[0, 1]));
- }
- else
- {
- for (int x = 0; x < matrix.GetLength(0); x++)
- {
- int subi = 0;
- for (int i = 1; i < matrix.GetLength(0); i++)
- {
- int subj = 0;
- for (int j = 0; j < matrix.GetLength(0); j++)
- {
- if (j == x)
- {
- continue;
- }
- submatrix[subi, subj] = matrix[i, j];
- subj++;
- }
- subi++;
- }
- det = det + (int)(Math.Pow(-1, x) * matrix[0, x] * CalculateDeterminant(submatrix));
- }
- }
- return det;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement