第三章第三题(代数:求解2 * 2线性方程)(Algebra: solve 2 * 2 linear equations)

    科技2022-07-12  122

    第三章第三题(代数:求解2 * 2线性方程)(Algebra: solve 2 * 2 linear equations)

    *3.3(代数:求解2 * 2线性方程)可以使用编程练习题1.13中给出的Cramer规则解线性方程组:

    编写程序,提示用户输入a, b, c, d, e 和 f,然后显示结果。如果 ad - bc为0,则报告消息 “The equation has no solution”(方程式无解)。 这里有些运行示例:

    Here are some simple runs:

    Enter a, b, c, d, e, f:9.0 4.0 3.0 -5.0 -6.0 -21.0

    x is -2.0 and y is 3.0

    Enter a, b, c, d, e, f:1.0 2.0 2.0 4.0 4.0 5.0

    The equation has no solution

    *3.3(Algebra: solve 2 * 2 linear equations) A linear equation can be solved using Cramer’s rule given in Programming Exercise 1.13. Write a program that prompts the user to enter a, b, c, d, e and f and displays the result. If ad - bc is 0, report that “The equation has no solution.” Here are some simple runs:

    Enter a, b, c, d, e, f:9.0 4.0 3.0 -5.0 -6.0 -21.0

    x is -2.0 and y is 3.0

    Enter a, b, c, d, e, f:1.0 2.0 2.0 4.0 4.0 5.0

    The equation has no solution

    参考代码:

    package chapter03; import java.util.Scanner; public class Code_03 { public static void main(String[] args){ Scanner input = new Scanner(System.in); System.out.print("Enter a,b,c,d,e,f: "); double a = input.nextDouble(); double b = input.nextDouble(); double c = input.nextDouble(); double d = input.nextDouble(); double e = input.nextDouble(); double f = input.nextDouble(); double medius = a * d - b * c; if (medius == 0){ System.out.println("The eqution has no solution"); } else{ double x = (e * d - b * f) / medius; double y = (a * f - e * c) / medius; System.out.println("x is " + x + " and y is " + y); } } } 结果显示: Enter a,b,c,d,e,f: 1.0 2.0 2.0 4.0 4.0 5.0 The eqution has no solution Process finished with exit code 0
    Processed: 0.011, SQL: 8