#include<iostream.h>
#include<stdlib.h>
#define p(i,x) p[(i)*(n+1)+x]
char suoming()
{ cout<<"if use Jacobi diedai,please input j:\n";
cout<<"if use Gauss-Seidel diedai,please input g:\n";
cout<<"if use SOR diedai,please input s:\n";
cout<<"input a char:";
char c;
cin>>c;
return c;
}
void huhuan(float *p1,float *p2,int n)
{ int i;
float s;
for(i=0;i<n;++i)
{ s=p1[i];p1[i]=p2[i];p2[i]=s;
}
}
void jdiedai(float *p,float *p1,float *p2,int n)
{ int i,j;
float s;
for(i=0;i<n;++i)
{ s=0;
for(j=0;j<n;++j)
{ if(j==i) continue;
s+=p(i,j)*p2[j];
}
p1[i]=(p(i,n)-s)/p(i,i);
}
}
void sordiedai(float *p,float *p1,float *p2,int n,float w)
{ int i,j;
float s;
for(i=0;i<n;++i)
{ s=0;
if(i>0)
for(j=0;j<i;++j)
s+=p(i,j)*p1[j];
for(j=i;j<n;++j)
s+=p(i,j)*p2[j];
p1[i]=p2[i]+w*(p(i,n)-s)/p(i,i);
}
}
float f(float s,float t)
{ if(s-t<0) return t-s;
else return s-t;
}
float wuqiongfan(float *p1,float *p2,int n)
{ int i,j;
float s=0,t=0;
for(i=0;i<n;++i)
{ if(i==0)
for(j=0;j<n;++j)
s+=f(p1[j],p2[j]);
for(j=1;j<n;++j)
t+=f(p1[j],p2[j]);
if(s<t) s=t;
t=0;
}
return s;
}
void main()
{ int i,x,n;
float *p,*p1,*p2,w,epc,s=10,k=0;
char c;
cout<<"input the number of equations:";
cin>>n;
p=new float[n*(n+1)];
p1=new float[n];
p2=new float[n];
cout<<"input A["<<n<<"*"<<n<<"]:\n";
for(i=0;i<n;++i)
for(x=0;x<n;++x)
cin>>p(i,x);
cout<<"intput b[b1 .... b"<<n<<"]\n";
for(i=0;i<n;++i)
cin>>p(i,n);
for(i=0;i<n;++i)
p2[i]=0;
c=suoming();
cout<<"input kong zhi tiao jian:||X(k+1)-X(k)||<?";
cin>>epc;
if(c=='s') {cout<<"please input w:"; cin>>w;}
if(c=='g') w=1;
if(c!='j')
while(s>=epc)
{ k++;
sordiedai(p,p1,p2,n,w);
s=wuqiongfan(p1,p2,n);
if(s>=epc) huhuan(p1,p2,n);
}
if(c=='j')
while(s>=epc)
{ k++;
jdiedai(p,p1,p2,n);
s=wuqiongfan(p1,p2,n);
if(s>=epc) huhuan(p1,p2,n);
}
cout<<"No."<<k<<":"<<endl;
cout.precision(8);
cout.setf(ios::fixed);
for(i=0;i<n;++i)
cout<<p1[i]<<endl;
delete p;
delete p1;
delete p2;
}