第八章第三十题(代数:解答线性方程)(Algebra: solving linear equations)
-
*8.30(代数:解答线性方程)编写一个方程,解答下面的2x2线性方程组系统:
方法头为:
public static double[] linearEqation(double[][] a,double[] b)
如果a00a11-a01a10为0,方法返回null。编写一个测试程序,提示用户输入a00、a01、a10、a11、b0以及b1,并且显示结果。如果a00a11-a01a10为0,报告“方程无解”。运行示例和编程练习题3.3的类似。
*8.30(Algebra: solving linear equations)Write an equation to solve the following 2x2 linear equation system:
The method header is:
public static double[] linearEqation(double[][] a,double[] b)
If a00a11-a01a10 is 0, the method returns null. Write a test program, prompt the user to input A00, A01, A10, a11, B0 and B1, and display the results. If a00a11-a01a10 is 0, report “no solution to the equation”. The running example is similar to that in programming exercise 3.3. -
参考代码:
package chapter08; import java.util.Scanner; public class Code_30 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter a00,a01,a10,a11,b0,b1:"); double[][] a = new double[2][2]; double[] b = new double[2]; a[0][0] = input.nextDouble(); a[0][1] = input.nextDouble(); a[1][0] = input.nextDouble(); a[1][1] = input.nextDouble(); b[0] = input.nextDouble(); b[1] = input.nextDouble(); double[] number = linearEqation(a,b); System.out.print("x:" + number[0] + "\ny:" + number[1]); } public static double[] linearEqation(double[][] a,double[] b){ double[] answer = new double[2]; if (a[0][0] * a[1][1] - a[0][1] * a[1][0] == 0) return null; else{ answer[0] = (b[0] * a[1][1] - b[1] * a[0][1]) / (a[0][0] * a[1][1] - a[0][1] * a[1][0]); answer[1] = (b[1] * a[0][0] - b[0] * a[1][0]) / (a[0][0] * a[1][1] - a[0][1] * a[1][0]); } return answer; } }
-
结果显示:
Enter a00,a01,a10,a11,b0,b1:1 2 3 3 4 1 x:-3.3333333333333335 y:3.6666666666666665 Process finished with exit code 0