让我们通过一个示例来看看线性方程组的形式:
我们需要将系数和变量的输入纳入考虑范围。整个过程主要包含以下几个步骤:
- 首先,我们需要在程序中导入 Scanner 包,以便使用 Scanner 类的对象来获取用户输入。
- 接着,初始化一个数组来存储方程组中的变量。
- 借助 Scanner 类的对象,从用户那里获取变量的系数。
- 最后,通过循环结构,将这些方程转换为矩阵的形式。
我们将通过两个示例来进行演示:
- 矩阵形式的3变量线性方程组。
- 矩阵形式的N变量线性方程组。
示例演示: 让我们先考虑数学中最常用的实际线性方程,即3变量线性方程。
**输入:** ax + by + cz = d
**输出:** 1 2 3 x = 10
5 1 3 y = 12
7 4 2 z = 20
示例 1: 3变量线性方程组矩阵形式的 Java 程序。
Java
CODEBLOCK_3bb9b0c2
输出结果:
现在,让我们将其推广到任意 N 值的情况:“n变量线性方程”。
示例演示:
**输入:** ax + by + cz + ... = d
**输出:** 1 2 3 x = 10
5 1 3 y = 12
7 4 2 z = 20
...
...
示例 2: N变量线性方程组矩阵形式的 Java 程序。
Java
`
import java.util.Scanner;
public class Linear_Equations_n {
public static void main(String args[])
{
System.out.println(
"******** n variable linear equation ********");
// Initializing the variables
char[] variable
= { ‘a‘, ‘b‘, ‘c‘, ‘x‘, ‘y‘, ‘z‘, ‘w‘ };
System.out.println("Enter the number of variables");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
System.out.println(
"Enter the coefficients variable");
System.out.println(
"Enter in the format shown below");
System.out.println("ax + by + cz + ... = d");
// Input of coefficients from user
int[][] matrix = new int[num][num];
int[][] constt = new int[num][1];
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
matrix[i][j] = sc.nextInt();
}
constt[i][0] = sc.nextInt();
}
// Representation of linear equations in form of
// matrix
System.out.println(
"Matrix representation of above linear equations is: ");
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
System.out.print(" " + matrix[i][j]);
}
System.out.print(" " + variable[i]);
System.out.print(" = " + constt[i][0]);
System.out.println();
}
sc.close();
}
}