高斯消元法(01)

using System;

namespace 高斯消元法解线性方程
{
    class Program
    {
        const int MAX = 10;
        static double[,] A = new double[MAX, MAX];
        static double[] b = new double[MAX];
        static double[] X = new double[MAX];
        static int NUM;
        static void Main(string[] args)
        {

            int i, j, k;
            double mik;//消元过程所用变量
            double S;//回代过程所用变量
            Input_Matrix();
            //消元
            for (k = 0; k < NUM - 1; k++)
            {
                if (A[k, k] == 0)
                    return;
                for (i = k + 1; i < NUM; i++)
                {
                    mik = A[i, k] / A[k, k];
                    for (j = k; j < NUM; j++)
                    {
                        A[i, j] = A[i, j] - mik * A[k, j];
                    }
                    b[i] = b[i] - mik * b[k];
                }
            }
            Console.WriteLine("消元后的矩阵A:");
            for (i = 0; i < NUM; i++)
            {
                for (j = 0; j < NUM; j++)
                    Console.Write("{0}\t", A[i, j]);
                Console.WriteLine();
            }
            Console.WriteLine("消元后的右端项b:\n\n");
            for (i = 0; i < NUM; i++)
                Console.Write("{0}\t", b[i]);
            //回代
            X[NUM - 1] = b[NUM - 1] / A[NUM - 1, NUM - 1];
            for (k = NUM - 2; k >= 0; k--)
            {
                S = b[k];
                for (j = k + 1; j < NUM; j++)
                {
                    S = S - A[k, j] * X[j];
                }
                X[k] = S / A[k, k];
            }
            Console.WriteLine();

            Console.WriteLine("结果\n\n");
            for (i = 0; i < NUM; i++)
                Console.Write("x{0}={1}\n", i+1,X[i]);
            return;

        }
        static void Input_Matrix()//输入矩阵
        {
            int i, j;
            Console.WriteLine("系数矩阵A的阶数:");
            NUM = int.Parse(Console.ReadLine());
            for (i = 1; i <= NUM; i++)
            {
                Console.WriteLine("系数矩阵A的第{0}行元素:", i);
                for (j = 1; j <= NUM; j++)
                    A[i - 1, j - 1] = double.Parse(Console.ReadLine());
            }
            Console.WriteLine("右端项b:");
            for (i = 1; i <= NUM; i++)
            {
                b[i - 1] = double.Parse(Console.ReadLine());
            }
            Console.WriteLine("输入的系数矩阵A:\n");
            for (i = 0; i < NUM; i++)
            {
                for (j = 0; j < NUM; j++)
                    Console.Write("{0}\t", A[i, j]);
                Console.WriteLine();

            }
            Console.WriteLine();

            Console.WriteLine("输入的右端项b:");
            for (i = 0; i < NUM; i++)
            {
                Console.Write("{0}\t", b[i]);
                Console.WriteLine();

            }


        }

    }
}

高斯消元法(01)_第1张图片

你可能感兴趣的:(C#)