每次寻找同一列最大系数所在的行数并交换到与列数相等的行数。后用正常解方程思想消掉这一列的系数只剩下最大系数的主元
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<cstring>
using namespace std;
double a[11451][11451];
int n;
inline double find_pivot( int column /*列数*/) {
//一列中最大的系数为主元
//并寻找这一列主元所在的行数
int maxn = column;
for (int i = column + 1; i <= n; ++i) {
if ( fabs( a[i][column] ) > fabs( a[maxn][column] ) ) {
maxn = i;
}
}
return maxn;
}
inline void swap_line( int beg , int end ) {
//让beg行交换主元最大的end行
for (int i = 1; i <= n + 1; ++i) {
swap( a[beg][i] , a[end][i] );
}
return;
}
int main()
{
scanf("%d",&n);
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= n + 1; ++j) {
scanf("%lf",&a[i][j]);
}
}
for (int i = 1; i <= n; ++i) {
double pivot = find_pivot ( i );//主元所在的行
swap_line ( i , pivot );
if ( a[i][i] == 0 ) {
//存在一列的系数均为0
//则这一列的未知数一定无解
printf("No Solution\n");
return 0;
}
for (int j = 1; j <= n; ++j) {
if ( j != i ) {
double temp = a[j][i] / a[i][i];
//算出第j行的第i列与主元的倍数关系
for (int k = i; k <= n + 1; ++k) {
a[j][k] -= ( a[i][k] * temp );
//消去与主元同一列的系数
}
}
}
}
for (int i = 1; i <= n; ++i) {
a[i][n + 1] /= a[i][i];
//将最后的结果除以第i项的系数
}
for (int i = 1; i <= n; ++i) {
printf("%.2lf\n",a[i][n + 1]);
}
return 0;
}
标签:高斯,int,主元,column,maxn,约旦,消元,include,行数
From: https://www.cnblogs.com/jueqingfeng/p/17119840.html