贴上代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 数值分析实验报告
{
class Gauss列主元素消去法
{
static void Main()
{
//Gauss列主元素消去法
int x = 0;
int y = 0;
Console.WriteLine("请指定增广矩阵的行数:");
x = int.Parse(Console.ReadLine());
Console.WriteLine("请指定增广矩阵的列数:");
y = int.Parse(Console.ReadLine());
double[,] Matrix = new double[x, y];
Console.WriteLine("请输入方程组的增广矩阵:");
string strMatrix = Console.ReadLine();
string[] MatrixArr = strMatrix.Split(' ');
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
Matrix[i, j] = double.Parse(MatrixArr[j + i * y].ToString());
}
}
Console.WriteLine("您输入的方程组的增广矩阵为:");
outMatrix(Matrix, x, y);
TranX(Matrix, x, y);
Console.ReadLine();
}
#region Gauss列主元消去法
//输入增广矩阵
private static void imputMatrix()
{
int x=0;
int y=0;
Console.WriteLine("请指定增广矩阵的行数:");
x = int.Parse(Console.ReadLine());
Console.WriteLine("请指定增广矩阵的列数:");
y = int.Parse(Console.ReadLine());
double[,] Matrix=new double[x,y];
Console.WriteLine("请输入方程组的增广矩阵:");
string strMatrix = Console.ReadLine();
string[] MatrixArr = strMatrix.Split(' ');
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
Matrix[i, j] = strMatrix[i+y];
}
}
Console.WriteLine("您输入的方程组的增广矩阵为:");
outMatrix(Matrix, x, y);
}
//输出矩阵
private static void outMatrix(double[,] Matrix,int x,int y)
{
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
Console.Write(Matrix[i, j] + "\t");
}
Console.WriteLine();
}
}
//变换矩阵
private static void TranX(double[,] Matrix, int x, int y)
{
double N = 0;
int p = 0;
for (int col = 0; col < y; col++)
{
double M = 0;
//这个循环获取列主元素
for (int row = col; row < x; row++)
{
if (Math.Abs(Matrix[row, col]) > Math.Abs(M))
{
M = Matrix[row, col];//列主元素
p = row; //列主元素所在的行
}
}
//这个循环进行行变换
for (int col1 = col; col1 < y; col1++)
{
N = Matrix[p, col1];
if (col != x) //由于增广矩阵是n*n+1阶,因此这里要进行判断,否则会提示数组越界错误
{
Matrix[p, col1] = Matrix[col, col1];
Matrix[col, col1] = N;
}
}
Console.WriteLine("经过第{0}次列主元变换后的矩阵为:", col + 1);
outMatrix(Matrix, x, y);
for (int row = col + 1; row < x; row++)
{
N = Matrix[row, col] / Matrix[col, col];//从col+1行开始,将第col列元素除以列主元素
for (int j = col; j < y; j++)
{
Matrix[row, j] = Matrix[row, j] - N * Matrix[col, j];
}
}
Console.WriteLine("第{0}次消元后的矩阵为:", col + 1);
outMatrix(Matrix, x, y);
}
Console.WriteLine("Gauss消元变换后的矩阵为:");
outMatrix(Matrix, x, y);
double[,] Result=new double[1,y-1];
//int num = 0;
for (int i = x - 1; i >= 0; i--)
{
double num = 0;
for (int n = 1; n < x - i; n++)
{
num += Result[0, y - (n+1)] * Matrix[i, y - (n+1)];
}
Result[0, y - (x - i + 1)] = (Matrix[i, y - 1] - num) / Matrix[i, y - (x - i + 1)];
}
Console.WriteLine("Gauss主元消去法计算的解为:");
outMatrix(Result, 1, y - 1);
Console.ReadLine();
}
#endregion
}
}
这个程序只是验证了一个方程组,也就是说并不能适合所有方程组,而且,代码和实现思想都很粗糙,希望大家多多指教!不过,由于付出了些许辛苦,所以拿出来和大家分享分享,也当作一种纪念吧!