📄 equationsolver.java
字号:
public class EquationSolver {
public static void swapRows(double matrix[][], int row1, int row2) {
for (int col = 0; col < matrix[row1].length; col++) {
double tmp = matrix[row1][col];
matrix[row1][col] = matrix[row2][col];
matrix[row2][col] = tmp;
}
}
public static void multRow(double matrix[][], double number, int row) {
for (int col = 0; col < matrix[row].length; col++) {
matrix[row][col] *= number;
}
}
public static void addRows(double matrix[][], double num, int row1, int row2) {
for (int col = 0; col < matrix[row1].length; col++) {
matrix[row2][col] += num * matrix[row1][col];
}
}
public static boolean foundNonZeroDiag(double matrix[][], int diag) {
for (int row = diag; row < matrix.length; row++) {
if (matrix[row][diag] != 0) {
swapRows(matrix, row, diag);
return true;
}
}
return false;
}
public static void normalizeColumn(double matrix[][], int col) {
multRow(matrix, 1.0 / matrix[col][col], col);
for (int row = 0; row < matrix.length; row++) {
if (row != col) {
addRows(matrix, -matrix[row][col], col, row);
}
}
}
public static boolean normalizeMatrix(double matrix[][]) {
for (int col = 0; col < matrix.length; col++) {
if (foundNonZeroDiag(matrix, col)) {
normalizeColumn(matrix, col);
}
else {
return false;
}
}
return true;
}
public static void showMatrix(double matrix[][]) {
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[row].length; col++) {
System.out.print(matrix[row][col] + "\t");
}
System.out.print("\n");
}
System.out.print("\n");
}
public static double[][] createMatrix() {
System.out.print("Enter number of variables: ");
int numVars = Console.readInt();
double matrix[][] = new double[numVars][numVars + 1];
for (int row = 0; row < numVars; row++) {
for (int col = 0; col < numVars; col++) {
System.out.print("Coefficient row " + (row + 1) +
", column " + (col + 1) + ": ");
matrix[row][col] = Console.readDouble();
}
System.out.print("Right-hand side for row " + (row + 1) + ": ");
matrix[row][numVars] = Console.readDouble();
}
return matrix;
}
public static void main(String args[]) {
double matrix[][] = createMatrix();
showMatrix(matrix);
if (normalizeMatrix(matrix)) {
showMatrix(matrix);
}
else {
System.out.println("No solution or no unique solution");
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -