最近幾天學習高等代數老師說要寫個程式算行列式的結果,閑來無事就簡單寫了一下。
不多說了,上代碼
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace Nrow_culmn
7 {
8 class Program
9 {
10 //計算行列式 計算複雜度為O(n的3次方)
11 public static double jlength = 0;
12 static void Main(string[] args)
13 {
14 //double[,] row_culmn = { { 3, 1, -1, 1 }, { 1, -1, 1, 2 }, { 2, 1, 2, -1 }, { 1, 0, 2, 1, } };
15 //行列式二維數組
16 double[,] row_culmn = { { 1, 4, 9, 16, 8 }, { 4, 9, 16, 25, 4 }, { 9, 16, 25, 36, 0 }, { 16, 25, 36, 49, 10 }, { 3, 15, 3, 69, 11 } };
17
18 //計算行列式的階數
19 jlength = Math.Sqrt(row_culmn.Length);
20
21 Console.WriteLine("原始行列式為:");
22 for (int i = 0; i < jlength; i++)
23 {
24 for (int j = 0; j < jlength; j++)
25 {
26 Console.Write(row_culmn[i, j].ToString() + " ");
27 }
28 Console.WriteLine();
29 }
30 Console.WriteLine();
31 Console.WriteLine();
32 Console.WriteLine();
33 int row = 0;//行 數組行列下标從0開始
34
35 int rowup = 1;//向右移動的偏移列(相對行)
36
37 for (row = 0; row < jlength - 1; row++)
38 {
39 //遞歸算法将行列式計算為做下三角全為0
40 ValueRow_Culmn(ref row_culmn, ref row, rowup);
41 rowup++;
42 }
43 //計算行列式的值double值不能預設等于0 否則會所有值都為零
44 double a = 1;
45 for (int i = 0; i < jlength; i++)
46 {
47 Console.WriteLine("第" + (i + 1) + "行 第" + (i + 1) + "列" + row_culmn[i, i]);
48 a *= row_culmn[i, i];
49 }
50 //格式化輸出
51 Console.WriteLine("最後得:");
52 Console.WriteLine(string.Format("{0:F}",a));
53 Console.ReadLine();
54
55 }
56
57 public static void ValueRow_Culmn(ref double[,] rc, ref int row, int rowup)
58 {
59 //double jlength = Math.Sqrt(rc.Length);
60 double k;//與列相乘的系數
61 if (rowup < jlength)
62 {
63 //計算行列式系數(第i行比第i-1行)
64 k = -rc[rowup, row] / rc[row, row];
65 //通過相乘系數 計算第i行的值
66 for (int j = 0; j < jlength; j++)
67 {
68 rc[rowup, j] += rc[row, j] * k;
69 }
70
71 Console.WriteLine();
72 Console.WriteLine();
73 //列印計算之後的行列式
74
75 for (int m = 0; m < jlength; m++)
76 {
77 for (int j = 0; j < jlength; j++)
78 {
79 Console.Write(rc[m, j].ToString() + " ");
80 }
81 Console.WriteLine();
82 }
83
84 Console.WriteLine();
85 //向下移動行
86 rowup++;
87 //遞歸調用方法函數
88 ValueRow_Culmn(ref rc, ref row, rowup);
89 }
90 else
91 { return; }
92 }
93
94
95
96 }
97 }