欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言实现高斯主元素法

程序员文章站 2022-06-01 22:49:17
...
#include<stdio.h>
#define Col 4//列数
#define Row 3//行数
void Print(double a[Row][Col]) {//打印a数组
	for (int i = 0; i < Row; i++)//找到最大主元,记录行号和列号
	{
		for (int j = 0; j < Col; j++)
		{
			printf("%f  ", a[i][j]);
		}
		printf("\n");
	}
	printf("\n");
}

void  ColumnSwap(double a[Row][Col],int m,int n) //m和n列交换
{
	double temp;
	for (int i = 0; i < Row;i++) 
	{
		temp = a[i][m];
		a[i][m] = a[i][n];
		a[i][n] = temp;
	}
}

void  RowSwap(double a[Row][Col], int m, int n) //m和n行交换
{
	double temp;
	for (int i = 0; i < Col; i++)
	{
		temp = a[m][i];
		a[m][i] = a[n][i];
		a[n][i] = temp;
	}
}
void Compute(double a[Row][Col], double result[Col - 1])//给定上三角矩阵,求解
{
	for (int i = Col - 2; i >= 0; i--)//求列主元的值
	{
		double sum = 0;
		//求sum
		for (int j = Col - 2; j > i; j--)
		{
			sum = sum + a[i][j] * result[j];
		}
		//求result解
		result[i] = (a[i][Col - 1] - sum) / a[i][i];
	}
}
void  SelectColumn(double a[Row][Col], int n) //找列主元
{
	double Max;
	int RowNum=n;
	Max = a[n][n];
	for (int i = n; i < Row  ; i++)//找到最大列主元,记录行号
	{
		if (a[i][n] > Max) 
		{
			Max = a[i][n];
			RowNum = i;
		}
	}
	RowSwap(a, RowNum, n);//两行交换
}
void  SelectTotal(double a[Row][Col], int n) //找全主元
{
	double Max;
	int   RowNum = n,ColNum = n;
	Max = a[n][n];
	for (int i = n; i < Row; i++)//找到最大主元,记录行号和列号
	{
		for (int j = n; j < Col-1; j++)
		{
			if (a[i][j] > Max)
			{
				Max = a[i][j];
				RowNum = i;
				ColNum = j;
			}
		}	
	}
	RowSwap(a, RowNum, n);//两行交换
	ColumnSwap(a, ColNum, n);//两列交换
}

void ColumnEliminate(double a[Row][Col],double result[Col-1])//高斯列主元素消去法
{
	double MainElem, Elem;//主元,普通元
	for (int i = 0; i < Row; i++)
	{
		SelectColumn(a, i); //找列主元
		Print(a);
		MainElem = a[i][i];
		for (int row = i+1; row < Row; row++)
		{
			Elem = a[row][i];
			for (int col = i; col < Col; col++)
			{
				a[row][col] = a[row][col] + Elem*a[i][col] * (-1) / MainElem;
			}
		}
		Print(a);
	}
	Compute(a, result);
}
void TotalEliminate(double a[Row][Col], double result[Col - 1])//高斯全主元素消去法
{
	double MainElem, Elem;//主元,普通元
	for (int i = 0; i < Row; i++)
	{
		SelectTotal(a, i); //找列主元
		Print(a);
		MainElem = a[i][i];
		for (int row = i + 1; row < Row; row++)
		{
			Elem = a[row][i];
			for (int col = i; col < Col; col++)
			{
				a[row][col] = a[row][col] + Elem*a[i][col] * (-1) / MainElem;
			}
		}
		Print(a);
	}
	Compute(a, result);
}

int main()
{
	double a[3][4] = { { 0.5, 1.1, 3.1, 6.0 },
						{ 2.0, 4.5, 0.36,0.020},
						{ 5.0, 0.96,6.5, 0.96 }, };
	double result[Col-1];
	ColumnEliminate(a, result);//列主元消去法
	//TotalEliminate(a, result);//全主元消去法,上下方法每次只能用一种
	Print(a);
	printf("result=\n");
	for (int i = 0; i <Col - 1; i++)
	{
		printf("%f ",result[i]);
	}
	getchar();
}