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,ref int []lz){Console.Write("请输入方程的阶数:");//Parese函数:将数字型的string字符转化为int型(类型转化)n = int.Parse(Console.ReadLine());lz = new int[n];for(int k = 0; k < n; k++){lz[k] = k + 1;}//开辟内存,指定下标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 FindMax(int k, int n, double[,] a, ref int[] IJ){double Max = a[k, k];int x = k;int y = k;for(int i = k; i <= n - 1; i++){for(int j = k; j <= n - 1; j++){if (a[i, j] > Max){x = i;y = j;Max = a[i, j];}}}IJ[0] = x;IJ[1] = y;}//行列交换static void Exchange(int n, int k, ref double[,] a, int[] IJ,ref int[] lz){double teap;if (IJ[0] != k){for (int j = k; j <= n; j++){//交换行teap = a[k, j];a[k, j] = a[IJ[0], j];a[IJ[0], j] = teap;}}if (IJ[1] != k){for (int i = k; i <= n - 1; i++){//交换列teap = a[i, k];a[i, k] = a[i, IJ[1]];a[i, IJ[1]] = teap;}//更改数组 lz int col = lz[k];lz[k] = lz[IJ[1]];lz[IJ[1]] = col;}}//消元static void Elimination(int n, ref double[,] a,ref int[] IJ,int[] lz){//注:i和j的初值不可以为2,因为,他们是随着k而变化的for (int k = 0; k <= n - 2; k++){FindMax(k, n, a,ref IJ);Exchange(n, k, ref a, IJ, ref lz);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;}Console.WriteLine($"\n——————————第{k+1}次消元结果——————————\n");OutPut(n, a);}}//回代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,int[] lz){for (int i = 1; i <= x.Length; i++){int k = Array.IndexOf(lz, i);//直接进行搜索//BinarySearch(lz ,i)——效率更高,但是因为它所采取的索引方法为二分法,所以需要事先排序//int k=Array.BinarySearch(lz ,i);//Console.WriteLine($"K[{i}]={k}");——调试用Console.WriteLine("X[{0}]={1,8:F2}", i, x[k]);}}//输出数组 lz 的值(测试用)static void OutPut(int [] x){for (int i = 0; i < x.Length; i++)Console.Write("{0} ", x[i]);}static void Main(string[] args){int n = 0;double[,] a = null;int[] lz = null;//记录下标int[] IJ = new int[2];//记录最大值的行列值double[] x = null;//输入数据InPut(ref n, ref a, ref lz);OutPut(lz);Console.WriteLine("\n——————————方程系数如下——————————\n");OutPut(n, a);//消元Elimination(n, ref a, ref IJ, lz);Console.WriteLine("\n————————方程最终消元结果如下————————\n");OutPut(n, a);BackSubstitution(n, a, ref x);Console.WriteLine("\n——————————方程的解如下——————————\n");OutPut(x, lz);//OutPut(lz);Console.Read();}}}
700字范文,内容丰富有趣,生活中的好帮手!