lineapproach.cpp

来自「这是我编写的一些关于数值分析算法」· C++ 代码 · 共 73 行

CPP
73
字号
// LineApproach.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <math.h>
#include <iostream.h>
#define n 3

void Gauss(double a[n][n],double b[n]);
void Exchange(double a[n][n],double b[n],int i);

int main(int argc, char* argv[])
{
	double a[3][3]={{2,6,-4},{1,4,-5},{6,-1,18}};
    double b[3]={4,3,2};
	Gauss(a,b);
	for (int i=0;i<n;i++)
	{
		cout<<b[i]<<endl;
	}
	return 0;
}

void Gauss(double a[n][n],double b[n])
{
    double temp;
	for (int i=0;i<n-1;i++)
	{
		Exchange(a,b,i);
		for(int j=i+1;j<n;j++)
		{
			temp=a[j][i];
			for (int k=i;k<n;k++)
			{
				a[j][k]-=((a[i][k])*(temp/a[i][i]));
			}
			
			b[j]-=b[i]*(temp/a[i][i]);
		}
	}
	for(i=n-1;i>=0;i--)
	{
		temp=0;
		for(int j=i+1;j<=n-1;j++)
			temp+=a[i][j]*b[j];
		b[i]=(b[i]-temp)/a[i][i];
	}
}

void Exchange(double a[n][n],double b[],int i)
{
	int k=i;
	double temp;
	double max=fabs(a[i][i]);
	for (int j=i+1;j<n;j++)
	{
		if(fabs(a[j][i])>max)
		{
			max=fabs(a[j][i]);
			k=j;
		}
	}
	temp=b[i];
	b[i]=b[k];
	b[k]=temp;
	for (j=i;j<n;j++)
	{
		temp=a[i][j];
		a[i][j]=a[k][j];
		a[k][j]=temp;
	}
}

⌨️ 快捷键说明

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