第七章第二十五题(代数:解一元二次方程式)(Algebra: solving quadratic equations of one variable)

公羊喜
2023-12-01

第七章第二十五题(代数:解一元二次方程式)(Algebra: solving quadratic equations of one variable)

  • 7.25(代数:解一元二次方程式)使用下面的方法头编写一个解一元二次方程式的方法:
    public static int solveQuadratic(double[] eqn,double[] roots)
    将一元二次方程ax2+bx+c=0的系数传给数组eqn,然后将两个实数根存在roots里。方法返回实数根的个数。参见编程习题3.1了解如何解一元二次方程。
    编写一个程序,题数用户输入a、b和c的值,然后显示实数根的个数以及所有的实数根。
    7.25(Algebra: solving quadratic equations of one variable)Use the following method to write a method to solve a quadratic equation of one variable
    public static int solveQuadratic(double[] eqn,double[] roots)
    The coefficients of the univariate quadratic equation AX2 + BX + C = 0 are transferred to the array eqn, and then two real roots are stored in roots. Method returns the number of real roots. See programming exercise 3.1 to learn how to solve quadratic equations of one variable.
    Write a program, the number of questions user input a, B and C values, and then display the number of real roots and all the real roots.

  • 参考代码:

    package chapter07;
    
    import java.util.Scanner;
    
    public class Code_25 {
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            double[] eqn = new double[3];
    
            System.out.println("请输入a,b,c的值");
            for(int i = 0;i < eqn.length;i++) {
                eqn[i] = input.nextDouble();
            }
            double delta = Math.pow(eqn[1],2) - 4 * eqn[0] * eqn[2];
    
            double[] roots = new double[2];
            if (solveQuadratic(eqn,roots) == 0){
                System.out.println("没有实数根");
            }
            if (solveQuadratic(eqn,roots) == 1){
                roots[0] = ((-eqn[1]) + Math.sqrt(delta)) / (2 * eqn[0]);
                roots[1] = roots[0];
                System.out.print("有两个相等实数根:");
                System.out.println("r1 = r2 = " + roots[0]);
            }
            if (solveQuadratic(eqn,roots) == 2){
                roots[0] = ((-eqn[1]) + Math.sqrt(delta)) / (2 * eqn[0]);
                roots[1] = ((-eqn[1]) - Math.sqrt(delta))/(2 * eqn[0]);
                System.out.print("有两个不等实数根:");
                System.out.println("r1 = "+roots[0]+","+"r2 = " + roots[1]);
            }
        }
        public static int solveQuadratic(double[] eqn,double[] roots){
            double delta = Math.pow(eqn[1],2) - 4 * eqn[0] * eqn[2];
            if(delta > 0){
                return 2;
            }
            else if (delta == 0){
                return 1;
            }
            else return 0;
        }
    }
    
    
  • 结果显示:

    请输入a,b,c的值
    2 4 2
    有两个相等实数根:r1=r2=-1.0
    
    Process finished with exit code 0
    
    
 类似资料: