最近几天学习高等代数老师说要写个程序算行列式的结果,闲来无事就简单写了一下。
不多说了,上代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; namespace Nrow_culmn
{
class Program
{
//计算行列式 计算复杂度为O(n的3次方)
public static double jlength = ;
static void Main(string[] args)
{
//double[,] row_culmn = { { 3, 1, -1, 1 }, { 1, -1, 1, 2 }, { 2, 1, 2, -1 }, { 1, 0, 2, 1, } };
//行列式二维数组
double[,] row_culmn = { { , , , , }, { , , , , }, { , , , , }, { , , , , }, { , , , , } }; //计算行列式的阶数
jlength = Math.Sqrt(row_culmn.Length); Console.WriteLine("原始行列式为:");
for (int i = ; i < jlength; i++)
{
for (int j = ; j < jlength; j++)
{
Console.Write(row_culmn[i, j].ToString() + " ");
}
Console.WriteLine();
}
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
int row = ;//行 数组行列下标从0开始 int rowup = ;//向右移动的偏移列(相对行) for (row = ; row < jlength - ; row++)
{
//递归算法将行列式计算为做下三角全为0
ValueRow_Culmn(ref row_culmn, ref row, rowup);
rowup++;
}
//计算行列式的值double值不能默认等于0 否则会所有值都为零
double a = ;
for (int i = ; i < jlength; i++)
{
Console.WriteLine("第" + (i + ) + "行 第" + (i + ) + "列" + row_culmn[i, i]);
a *= row_culmn[i, i];
}
//格式化输出
Console.WriteLine("最后得:");
Console.WriteLine(string.Format("{0:F}",a));
Console.ReadLine(); } public static void ValueRow_Culmn(ref double[,] rc, ref int row, int rowup)
{
//double jlength = Math.Sqrt(rc.Length);
double k;//与列相乘的系数
if (rowup < jlength)
{
//计算行列式系数(第i行比第i-1行)
k = -rc[rowup, row] / rc[row, row];
//通过相乘系数 计算第i行的值
for (int j = ; j < jlength; j++)
{
rc[rowup, j] += rc[row, j] * k;
} Console.WriteLine();
Console.WriteLine();
//打印计算之后的行列式 for (int m = ; m < jlength; m++)
{
for (int j = ; j < jlength; j++)
{
Console.Write(rc[m, j].ToString() + " ");
}
Console.WriteLine();
} Console.WriteLine();
//向下移动行
rowup++;
//递归调用方法函数
ValueRow_Culmn(ref rc, ref row, rowup);
}
else
{ return; }
} }
}