/*
4
1.1348 3.8326 1.1651 3.4017 9.5342
0.5301 1.7875 2.533 1.5435 6.3941
3.4129 4.9317 8.7643 1.3142 18.431
1.2371 4.9998 10.6721 0.0147 16.9237
*/
#include <iostream>
using namespace std;
void Gauss(double **a,int n){
for(int time=0;time<n-1;time++){//消元部分
for(int i=time;i<n-1;i++){
double bs = -a[i+1][time]/a[time][time];
for(int j=0;j<n+1;j++){
a[i+1][j] += a[time][j]*bs;
}
}
}//以下开始回代
double answer[n];
answer[n-1] = a[n-1][n]/a[n-1][n-1];
for(int i=n-2;i>-1;i--){
double sum=a[i][n];
for(int j=n-1;j>i;j--){
sum-=answer[j]*a[i][j];
}
answer[i] = sum/a[i][i];
}//输出结果
cout<<"gauss :"<<endl;
for(int i=0;i<n;i++) cout<<answer[i]<<endl;
}
void CGauss(double **a,int n){
for(int time=0;time<n-1;time++){//消元部分
double max = abs(a[time][time]);//找到最大值
int pos = time;
for(int i=time+1;i<n;i++){
if(abs(a[i][time])>max){
max=abs(a[i][time]);
pos = i;
}
}//交换两列
if(pos!=time){
double temp;
for(int i=0;i<n+1;i++){
temp = a[time][i];
a[time][i] = a[pos][i];
a[pos][i] =temp;
}
}//消元
for(int i=time;i<n-1;i++){
double bs = -a[i+1][time]/a[time][time];
for(int j=0;j<n+1;j++){
a[i+1][j] += a[time][j]*bs;
}
}
/*观察每一步换行
for(int i=0;i<n;i++){
for(int j=0;j<n+1;j++) cout<<a[i][j]<<" ";
cout<<endl;
}
*/
}//回代
double answer[n];
answer[n-1] = a[n-1][n]/a[n-1][n-1];
for(int i=n-2;i>-1;i--){
double sum=a[i][n];
for(int j=n-1;j>i;j--){
sum-=answer[j]*a[i][j];
}
answer[i] = sum/a[i][i];
}
cout<<"C gauss :"<<endl;
for(int i=0;i<n;i++) cout<<answer[i]<<endl;
}
int main() {
int n;
cin >> n;
auto **a = new double* [n],**b = new double *[n];
for(int i=0;i<n;i++){
a[i] = new double [n+1];
b[i] = new double [n+1];
}
double temp;
for(int i=0;i<n;i++) for(int j=0;j<n+1;j++) {
cin >> temp;
a[i][j] =temp;
b[i][j] = temp;
}
Gauss(a,n);
CGauss(b,n);
for(int i=0;i<n;i++){//释放内存
delete []a[i];
delete []b[i];
}
delete [] a;
delete [] b;
return 0;
}
顺序高斯消元法以及列主元高斯消元法
于 2022-04-13 22:32:23 首次发布