最近几天学习高等代数老师说要写个程序算行列式的结果,闲来无事就简单写了一下。
不多说了,上代码
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 }