import java.util.Scanner;
public class Gauss {
static final int MAXN = 20;
static double a[][] = new double[MAXN][MAXN];
static double b[][] = new double[2][MAXN];//用来记录解出来的根,本题用一维数组即可,二维数组是为完全主元素消元法做准备
static int num;
public static void main(String[] args) {
System.out.println("输入未知数个数:");
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
System.out.println("输入用矩阵表示的线性方程组:");
for (int i = 0; i < num; i++) {//输入方程组
for (int j = 0; j <= num; j++) {
a[i][j] = sc.nextDouble();
}
}
for (int i = 0; i < num; i++) {//初始化计数数列
b[0][i] = i;
b[1][i] = 0;
}
for (int j = 0; j < num - 1; j++) {
paixu(j);
dengjia(j);
}
for (int i = num - 1; i >= 0; i--) {
jiefangcheng(i);
}
for (int j = 0; j < num; j++) {
System.out.println("x" + (j + 1) + "=" + b[1][j]);
}
}
static void dengjia(int jj) {//把原矩阵转化成三角形的
for (int i = jj + 1; i < num; i++) {
double k = a[i][jj] / a[jj][jj];
for (int j = jj; j <= num; j++) {
a[i][j] = a[i][j] - a[jj][j] * k;
}
}
}
static void jiefangcheng(int ii) {//解方程
for (int j = ii + 1; j < num; j++) {
a[ii][num] -= a[ii][j] * b[1][j];
}
b[1][ii] = a[ii][num] / a[ii][ii];
}
static void paixu(int jj) {//排序
for (int j = jj; j < num-1; j++) {
for (int k = jj; k < num - 1; k++) {
if (Math.abs(a[k][jj]) < Math.abs(a[k + 1][jj])) {
for (int i = jj; i <= num; i++) {
double temp = a[k][i];
a[k][i] = a[k + 1][i];
a[k + 1][i] = temp;
}
}
}
}
}
}
列主元法解线性方程组
最新推荐文章于 2022-04-16 22:50:46 发布