namespace 高斯列主元消去法解方程
{
class Program
{
static double[] Gause(double[,] a, int n)
{
int i, j,
k;
int rank,
columm;
double
temp,l,s;
double[] x
= new double[n];
for (i =
0; i <= n - 2; i++)
{
rank=i;
columm=i;
for(j=i+1;j<=n-1;j++)
//选主元
if (a[j, i] > a[i, i])
{
rank =
j;
columm =
i;
}
for (k = 0; k <= n; k++)
//主元行变换
{
temp = a[i, k];
a[i, k] = a[rank, k];
a[rank, k] = temp;
}
for (j = i + 1; j <= n -
1; j++)
//解线性方程
{
l = a[j, i] / a[i, i];
for (k = i; k <= n; k++)
a[j, k] =
a[j, k] - l * a[i, k];
}
}
x[n - 1] =
a[n - 1, n] / a[n - 1, n - 1];
//回代方程求解x
for (i = n
- 2; i >= 0; i--)
{
s = 0;
for (j = i + 1; j <= n -
1; j++)
s = s + a[i, j] * x[j];
x[i] = (a[i, n] - s) / a[i,
i];
}
return
x;
}
//设方程组一般形式:Ax=b,a数组是方程组系数矩阵A+向量b,即a=[A|b],x数组是方程组的解
static void Main(string[] args)
{
double[,]
a = new double[4, 5] { { 10, -7, 0, 1,8 }, { -3, 2.099999, 6,
2,5.900001 }, { 5,-1,5,-1,5 },{2,1,0,2,1} };
int n =
4;
double[] x
= new double[n];
x =
Gause(a, n);
Console.WriteLine("高斯消去法方程:");
for (int i
= 0; i < n; i++)
{
for (int j = 0; j < n;
j++)
Console.Write(a[i, j].ToString() + "
");
Console.WriteLine();
}
Console.WriteLine("线性方程组的解:");
for (int i
= 0; i <= n - 1; i++)
Console.Write("x" + (i +
1).ToString()+"="+x[i].ToString()+"
");
Console.WriteLine();
Console.ReadLine();
}
}
}
加载中,请稍候......