例题1:高斯消元解线性方程组
输入一个包含 n 个方程 n 个未知数的线性方程组。
方程组中的系数为实数。
求解这个方程组。
下图为一个包含 m 个方程 n 个未知数的线性方程组示例:
输入格式
第一行包含整数 n。
接下来 n 行,每行包含 n+1 个实数,表示一个方程的 n 个系数以及等号右侧的常数。
输出格式
如果给定线性方程组存在唯一解,则输出共 n 行,其中第 i 行输出第 i 个未知数的解,结果保留两位小数。
如果给定线性方程组存在无数解,则输出 Infinite group solutions
。
如果给定线性方程组无解,则输出 No solution
。
数据范围
1≤n≤100,
所有输入系数以及常数均保留两位小数,绝对值均不超过 100。
输入样例:
3
1.00 2.00 -1.00 -6.00
2.00 1.00 -3.00 -9.00
-1.00 -1.00 2.00 7.00
输出样例:
1.00
-2.00
3.00
答案:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static int n;
public static double a[][];
public static int N = 110;
public static double eps = 1e-6;
public static int gauss() {
int c, r;
for (c = 0, r = 0; c < n; c++) {
int t = r;
for (int i = r; i < n; i++)
if (Math.abs(a[i][c]) > Math.abs(a[t][c]))
t = i;
if (Math.abs(a[t][c]) < eps)
continue;
for (int i = c; i < n + 1; i++) {
double v = a[t][i];
a[t][i] = a[r][i];
a[r][i] = v;
}
for (int i = n; i >= c; i--) a[r][i] /= a[r][c];
for (int i = r + 1; i < n; i++)
if (Math.abs(a[i][c]) > eps)
for (int j = n; j >= c; j--)
a[i][j] -= a[r][j] * a[i][c];
r++;
}
if (r < n) {
for (int i = r; i < n; i++)
if (Math.abs(a[i][n]) > eps)
return 2;
return 1;
}
for (int i = n - 1; i >= 0; i--)
for (int j = i + 1; j < n; j++)
a[i][n] -= a[j][n] * a[i][j];
return 0;
}
public static void main(String[] args) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String[] str = bufferedReader.readLine().split(" ");
n = Integer.parseInt(str[0]);
a = new double[n + 1][n + 1];
for (int i = 0; i < n; i++) {
str = bufferedReader.readLine().split(" ");
for (int j = 0; j <= n; j++) {
a[i][j] = Double.parseDouble(str[j]);
}
}
int x = gauss();
//得出结果
if (x == 1) System.out.println("Infinite group solutions");
else if (x == 0)
for (int i = 0; i < n; i++)
System.out.println(String.format("%.2f", a[i][n]));
else
System.out.println("No solution");
}
}
println(String.format("%.2f", a[i][n]));
else
System.out.println("No solution");
}
}