⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 gauss.cpp

📁 高斯列主元消去法
💻 CPP
字号:
#include<math.h>
#include<stdlib.h>
#include<iostream.h>
#include<stdio.h>



void main()
{
	int i,j,n,k,i0;
	double eps,p,w;

	//输入方程组维数,增广矩阵系数和控制条件精度
	cout<<"please input the dimension of the matrix"<<endl;
	cin>>n;
    double **a;
    a=new double *[n];
    for(i=0;i<n;i++)
		a[i]=new double[n+1];
	for(i=0;i<n;i++)
	{
		cout<<"please input the data of row "<<i+1<<" : ";
		for(j=0;j<=n;j++)
			cin>>a[i][j];
	}
	cout<<"please input the eps"<<endl;
	cin>>eps;

	//消元
	for(k=0;k<n-1;k++)
	{
		p=a[k][k];
		i0=k;
		for(i=k;i<n;i++)
			if(fabs(a[i][k])>fabs(p))
			{
				p=a[i][k];
				i0=i;
			}
        if(fabs(p)<=eps)
		{
			cout<<"EXI=1"<<endl;
			exit(0);
		}
		if(i0!=k)
		    for(j=k;j<=n;j++)
			{
			    w=a[k][j];
		        a[k][j]=a[i0][j];
			    a[i0][j]=w;
			}
		for(i=k+1;i<n;i++)
		{
			a[i][k]=a[i][k]/a[k][k];
			for(j=k+1;j<=n;j++)
				a[i][j]=a[i][j]-a[i][k]*a[k][j];
		}
	}
	if(a[n-1][n-1]==0)
	{
		cout<<"EXI=1"<<endl;
		exit(0);
	}

	//回代
	a[n-1][n]=a[n-1][n]/a[n-1][n-1];
	for(k=n-2;k>=0;k--)
	{
		w=0;
		for(j=k+1;j<n;j++)
			w=w+a[k][j]*a[j][n];
		a[k][n]=a[k][n]-w;
		a[k][n]=a[k][n]/a[k][k];
	}
	cout<<"the root is:"<<endl;
	for(i=0;i<n;i++)
		cout<<"x"<<i+1<<"= "<<a[i][n]<<endl;
	free(a);
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -