按比例列选主元Gauss消去法求线性方程组的解

实习二

用按比例列选主元Gauss消去法求下列线性方程组Ax=b的解。

系数矩阵A:
15 7 6 5 1
7 10 8 7 2
6 8 10 9 3
5 7 9 10 4
1 2 3 4 5

右端向量b:

-4.0000
21.0000
13.2000
5.0000
-9.0000

要求:输出每次选取的主元的行号,解向量x.
输出时要有一定的文字说明,以使输出结果一目了然。

#include <iostream.h>
#include <fstream.h>
#include <stdlib.h>
#include <math.h>
void main()
{
char filename1[256],filename2[256];
cout<<"Enter the path to input file:";
cin>>filename1;
cout<<"Enter the path to output file:";
cin>>filename2;
ifstream infile(filename1,ios::in|ios::nocreate);
ofstream outfile(filename2);
if(!infile){
cout<<"Can’t open input file:"<<filename1<<’
’;
exit(1);
}

int k,m,i,j,n,w;
infile>>n;
w=n+1;

double *p,*x;
double t;

p=new double[w*w];
x=new double[w];
for(i=0;i<w;i++) p[i]=0;
for(i=w;i<w*w;i++)
infile>>p[i];

for(k=1;k<n;k++) //step 1

{
t=p[k*w+k-1];
m=k;
for(i=k;i<w;i++) //step 2
{ if(fabs(p[i*w+k-1])>fabs(t))
{ t=p[i*w+k-1];
m=i;
}
}
if(t<1e-8) //step 3
{ cout<<"A is singular"<<endl;
exit(2);
}
outfile<<"第"<<k<<"列的主元行号为:"<<m<<’
’;
//----------------------------------------
if(m!=k) //step 4
for(j=k;j<w+1;j++)
{ t=p[k*w+j-1];
p[k*w+j-1]=p[m*w+j-1];
p[m*w+j-1]=t;
}
for(i=k+1;i<w;i++) //step 5
{ p[i*w+k-1]=p[i*w+k-1]/p[k*w+k-1]; //step 6
for(j=k+1;j<w+1;j++) //step 7
p[i*w+j-1]=p[i*w+j-1]-p[i*w+k-1]*p[k*w+j-1];
}

}
x[n]=p[n*w+n]/p[n*w+n-1]; //step 8

for(k=n-1;k>0;k--) //step 9
{ t=0;
for(j=k+1;j<n+1;j++) t+=p[k*w+j-1]*x[j];
x[k]=(p[k*w+n]-t)/p[k*w+k-1];
}
outfile<<"方程组的根为:("; //step 10
for(i=1;i<n;i++)
outfile<<x[i]<<’,’;
outfile<<x[n]<<’)’;
infile.close();
outfile.close();

}
input===========

5
15 7 6 5 1 -4.0000
7 10 8 7 2 21.0000
6 8 10 9 3 13.2000
5 7 9 10 4 5.0000
1 2 3 4 5 -9.0000

output==========

第1列的主元行号为:1
第2列的主元行号为:2
第3列的主元行号为:3
第4列的主元行号为:4
方程组的根为:(-2.01506,3.73891,2.00518,-1.87662,-2.59436)

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注