標籤:
最近幾天學習高等代數老師說要寫個程式算行列式的結果,閑來無事就簡單寫了一下。
不多說了,上代碼
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 //遞迴演算法將行列式計算為做下三角全為038 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 else82 { return; }83 }84 85 86 87 }88 }
行列式計算(C#)