标签:
最近几天学习高等代数老师说要写个程序算行列式的结果,闲来无事就简单写了一下。
不多说了,上代码
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 public static double jlength = 0; 11 static void Main(string[] args) 12 { 13 //double[,] row_culmn = { { 3, 1, -1, 1 }, { 1, -1, 1, 2 }, { 2, 1, 2, -1 }, { 1, 0, 2, 1, } }; 14 //行列式二维数组 15 double[,] row_culmn = { { 1, 4, 9, 16 }, { 4, 9, 16, 25 }, { 9, 16, 25, 36 }, { 16, 25, 36, 49} }; 16 17 18 19 for (int i = 0; i < 4; i++) 20 { 21 for (int j = 0; j < 4; j++) 22 { 23 Console.Write(row_culmn[i, j].ToString() + " "); 24 } 25 Console.WriteLine(); 26 } 27 Console.WriteLine(); 28 Console.WriteLine(); 29 Console.WriteLine(); 30 int row = 0;//行 31 32 int rowup = 1;//向右移动的偏移列(相对行) 33 jlength = Math.Sqrt(row_culmn.Length); 34 35 for (row = 0; row < jlength - 1; row++) 36 { 37 //递归算法将行列式计算为做下三角全为0 38 ValueRow_Culmn(ref row_culmn, ref row, rowup); 39 rowup++; 40 } 41 //计算行列式的值double值不能默认等于0 否则会所有值都为零 42 double a = 1; 43 for (int i = 0; i < jlength; i++) 44 { 45 Console.WriteLine(row_culmn[i, i]); 46 a *= row_culmn[i, i]; 47 } 48 //格式化输出 49 Console.WriteLine(string.Format("{0:F}",a)); 50 Console.ReadLine(); 51 52 } 53 54 public static void ValueRow_Culmn(ref double[,] rc, ref int row, int rowup) 55 { 56 //double jlength = Math.Sqrt(rc.Length); 57 double k;//与列相乘的系数 58 if (rowup < jlength) 59 { 60 k = -rc[rowup, row] / rc[row, row]; 61 for (int j = 0; j < jlength; j++) 62 { 63 rc[rowup, j] += rc[row, j] * k; 64 } 65 66 Console.WriteLine(); 67 Console.WriteLine(); 68 for (int m = 0; m < 4; m++) 69 { 70 for (int j = 0; j < 4; j++) 71 { 72 Console.Write(rc[m, j].ToString() + " "); 73 } 74 Console.WriteLine(); 75 } 76 77 Console.WriteLine(); 78 rowup++; 79 ValueRow_Culmn(ref rc, ref row, rowup); 80 } 81 else 82 { return; } 83 } 84 85 86 87 } 88 }
标签:
原文地址:http://www.cnblogs.com/zhyg/p/4423483.html