using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 高斯列主元消元法
{
class Program
{
//输入参数
static void InPut(ref int n, ref double[,] a)
{
Console.Write("请输入方程的阶数:");
//Parese函数:将数字型的string字符转化为int型(类型转化)
n = int.Parse(Console.ReadLine());
//开辟内存,指定下标
a = new double[n, n + 1];
Console.WriteLine("请输入方程的系数:");
for (int i = 0; i < n; i++)
{
string r = Console.ReadLine();
//Split函数:将字符串r拆分
string[] rs = r.Split(' ');
for (int j = 0; j < n + 1; j++)
{
a[i, j] = double.Parse(rs[j]);
}
}
}
static void FindMaster(int k, ref double[,] a, int n)
{
bool flag = false;
double s = a[k, k];
int m = k;
for (int i = k + 1; i <= n - 1; i++)
{
if (Math.Abs(s) < Math.Abs(a[i, k]))
{
m = i;
s = a[i, k];
flag = true;
}
}
if (flag == true)
{
for (int v = k; v <= n; v++)
{
double t = a[k, v];
a[k, v] = a[m, v];
a[m, v] = t;
}
}
}
//消元
static void Elimination(int n, ref double[,] a)
{
//注:i和j的初值不可以为2,因为,他们是随着k而变化的
for (int k = 0; k <= n - 2; k++)
{
FindMaster(k, ref a, n);
for (int i = k + 1; i <= n - 1; i++)
{
double lik = a[i, k] / a[k, k];
for (int j = k + 1; j <= n; j++)
{
a[i, j] = a[i, j] - lik * a[k, j];
}
a[i, k] = 0;
}
}
}
//回代
static void BackSubstitution(int n, double[,] a, ref double[] x)
{
x = new double[n];
for (int i = n - 1; i >= 0; i--)
{
double sum = 0;
for (int j = i + 1; j <= n - 1; j++)
{
sum = sum + a[i, j] * x[j];
}
x[i] = (a[i, n] - sum) / a[i, i];
}
}
//方程系数输出
static void OutPut(int n, double[,] a)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n + 1; j++)
{
Console.Write("{0,8:F2}", a[i, j]);
}
//控制换行
Console.WriteLine();
}
}
//结果输出
static void OutPut(double[] x)
{
for (int i = 0; i < x.Length; i++)
Console.WriteLine("X[{0}]={1,8:F2}", i, x[i]);
}
static void Main(string[] args)
{
int n = 0;
double[,] a = { };
double[] x = { };
//输入数据
InPut(ref n, ref a);
Console.WriteLine("----------方程系数如下----------");
OutPut(n, a);
//消元
Elimination(n, ref a);
Console.WriteLine("----------消元后方程系数如下----------");
OutPut(n, a);
BackSubstitution(n, a, ref x);
Console.WriteLine("----------方程的解如下----------");
OutPut(x);
Console.Read();
}
}
}
高斯列主元消元法
最新推荐文章于 2022-09-25 15:00:03 发布