最后化简成
k1 * x1 = a
k2 * x2 = b
如果 k1 = 0 a != 0则无解
如果 k1 = 0 a = 0则无穷解
注意要先判断无解再判断无穷解QWQ
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
using namespace std;
int n,nowline;
double a[11451][11451];
inline int find_pivot( int line , int column ) {
//line:行 column:列
int maxn = line;
for (int i = line + 1; i <= n; ++i) {
if ( a[i][column] > a[maxn][column] ) {
maxn = i;
}
}
return maxn;
}
inline void swap_line( int now , int need ) {
//now表示现在这一行 need表示需要的行
for (int i = 1; i <= n + 1; ++i) {
swap( a[now][i] , a[need][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 q = 1,i = 1; q <= n; ++q) {
//i表示第几行 q表示第几列
int pivot = find_pivot( i , q );
//这里一定要注意find时的行与列 QWQ
if ( a[pivot][q] == 0 ) continue;
//如果此列全为0则先跳过,可以先不用管
swap_line( i , pivot );
for (int j = 1; j <= n; ++j) {
if ( j != i ) {
double temp = a[j][q] / a[i][q];
for (int k = q;k <= n + 1; ++k) {
a[j][k] -= ( a[i][k] * temp );
}
}
}//正常高斯约旦消元
i ++;
nowline = i;
}
if ( nowline <= n ) {
for (int i = nowline; i <= n; ++i) {
if ( a[i][n + 1] != 0 ) {
//其中有k * x = a;
//若 k = 0 a != 0 则无解 输出-1
//若 k = 0 a = 0 则无穷解 输出0
//注意在同时是无解和无穷解的情况下方程组属于无解
printf ("-1\n");
return 0;
}
}
printf ("0\n");
return 0;
}
for (int i = 1; i <= n; ++i) {
a[i][n + 1] /= a[i][i];//除上系数
printf ( "x%d=" , i );
if ( fabs( a[i][n + 1] ) == 0 ) a[i][n + 1] = 0;
printf ( "%.2lf\n" , a[i][n + 1] );
}
return 0;
}
标签:int,线性方程组,column,k1,maxn,line,include
From: https://www.cnblogs.com/jueqingfeng/p/17126206.html