Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- namespace Гаусс
- {
- internal class Program
- {
- static void Main(string[] args)
- {
- using (var sr = new StreamReader("input.txt"))
- {
- double[,] matrix;
- int n = int.Parse(sr.ReadLine());
- matrix = new double[n, n];
- for (int i = 0; i < n; i++)
- {
- string[] str = sr.ReadLine().Split(' ');
- for (int j = 0; j < n; j++)
- {
- matrix[i, j] = double.Parse(str[j]);
- }
- }
- PrintMatrix(matrix);
- Console.WriteLine();
- matrix = TriangleType(matrix);//Приведение к треугольному виду
- PrintMatrix(matrix);
- double det = GetDeterminant(matrix);
- Console.WriteLine("Определитель = "+det);
- Console.ReadKey();
- }
- }
- public static double[,] TriangleType(double[,] matrix)
- {
- int n = (int)Math.Sqrt(matrix.Length);
- for (int i = 0; i < n; i++)//строка
- {
- for (int j = i + 1; j < n; j++)//столбец
- {
- if(matrix[i,i] == 0)//Если на главной диагонали рассматриваемой строки 0
- {
- int indexElNotZero = -1;
- for (int t = i; t < n; t++)
- {
- if(matrix[t,i] !=0)//Ищем под этим нулём не нулевуб строку
- {
- indexElNotZero = t;
- }
- }
- if(indexElNotZero == -1)//Если таких строк нет, то выводим пустую матрицу --> det=0
- {
- matrix = new double[n, n];
- return matrix;
- }
- for (int k = 0; k < n; k++)//Если такая строка нашлась, то прибавляем её к той, где нуль
- {
- matrix[i, k] += matrix[indexElNotZero, k];
- }
- }
- double temp = matrix[j, i] / matrix[i, i];//Находим коэффициент
- for (int l = 0; l < n; l++)
- {
- matrix[j, l] = matrix[j, l] - temp * matrix[i, l];//Вычитаем из нижней строчки верхнюю, домноженную на коэфициент
- }
- }
- }
- return matrix;
- }
- public static void PrintMatrix(double[,] matrix)
- {
- int n = (int)Math.Sqrt(matrix.Length);
- for (int i = 0; i < n; i++)
- {
- for (int j = 0; j < n; j++)
- {
- Console.Write(matrix[i, j] + " ");
- }
- Console.WriteLine();
- }
- }
- public static double GetDeterminant(double[,] matrix)
- {
- int n = (int)Math.Sqrt(matrix.Length);
- double determinant = 1;
- for (int i = 0, j = 0; i < n; i++, j++)
- {
- determinant *= matrix[i, j];
- }
- return determinant;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement