java 求二次方程的根

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14389751/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:05:51  来源:igfitidea点击:

Finding roots of quadratic equation

java

提问by The Hidden Person

I have this code so far but every time i run and put the three numbers in a get the roots are NaN can some one please help or point me to where i went wrong.

到目前为止,我有这段代码,但是每次我运行并将三个数字放入一个 get 根是 NaN 时,有人可以帮忙或指出我出错的地方。

 import java.util.Scanner;

 class Quadratic {
   public static void main(String[] args) {

   System.out.println("Enter three coefficients");
   Scanner sc = new Scanner(System.in);
   double a = sc.nextDouble();
   double b = sc.nextDouble();
   double c = sc.nextDouble();
   double root1= (-b + Math.sqrt( b*b - 4*a*c ) )/ (2*a);
   double root2= (-b - Math.sqrt( b*b - 4*a*c ) )/ (2*a);
   System.out.println("The roots1 are: "+ root1);
   System.out.println("The roots2 are: " + root2);


     } 
   }

回答by arshajii

You have to remember that not every quadratic equation has roots that can be expressed in terms of real numbers. More specifically, if b*b - 4*a*c < 0, then the roots will have an imaginary part and NaNwill be returned, since Math.sqrtof a negative number returns NaN, as specified in the documentation. This works for coefficients such that b*b - 4*a*c >= 0, however:

您必须记住,并非每个二次方程都有可以用实数表示的根。更具体地说,如果b*b - 4*a*c < 0,则根将具有虚部并将NaN返回,因为Math.sqrt负数返回NaN,如文档中所述。这适用于这样的系数b*b - 4*a*c >= 0,但是:

Enter three coefficients
1
5
6
The roots1 are: -2.0
The roots2 are: -3.0


If you wanted to account for non-real roots as well, you could do something like

如果您还想考虑非实数根源,您可以执行以下操作

double d = (b * b - 4 * a * c);
double re = -b / (2 * a);

if (d >= 0) {  // i.e. "if roots are real"
    System.out.println(Math.sqrt(d) / (2 * a) + re);
    System.out.println(-Math.sqrt(d) / (2 * a) + re);
} else {
    System.out.println(re + " + " + (Math.sqrt(-d) / (2 * a)) + "i");
    System.out.println(re + " - " + (Math.sqrt(-d) / (2 * a)) + "i");
}

回答by Deepali Agg

You could use the following code. First, it will check whether input equation is quadratic or not. And if input equation is quadratic then it will find roots. This code is able to find complex roots too.

您可以使用以下代码。首先,它会检查输入方程是否是二次方程。如果输入方程是二次方程,那么它将找到根。此代码也能够找到复杂的根。

public static void main(String[] args) {

公共静态无效主(字符串 [] args){

    // Declaration of variables
    float a = 0, b = 0, c = 0, disc, sq_dis;
    float[] root = new float[2];
    StringBuffer number;
    Scanner scan = new Scanner(System.in);

    // Input equation from user
    System.out.println("Enter Equation in form of ax2+bx+c");
    String equation = scan.nextLine();

    // Regex for quadratic equation
    Pattern quadPattern = Pattern.compile("(([+-]?\d*)[Xx]2)+((([+-]?\d*)[Xx]2)*([+-]\d*[Xx])*([+-]\d+)*)*|((([+-]?\d*)[Xx]2)*([+-]\d*[Xx])*([+-]\d+)*)*(([+-]?\d*)[Xx]2)+|((([+-]?\d*)[Xx]2)*([+-]\d*[Xx])*([+-]\d+)*)*(([+-]?\d*)[Xx]2)+((([+-]?\d*)[Xx]2)*([+-]\d*[Xx])*([+-]\d+)*)*");
    Matcher quadMatcher = quadPattern.matcher(equation);
    scan.close();

    // Checking if given equation is quadratic or not
    if (!(quadMatcher.matches())) { 
        System.out.println("Not a quadratic equation");
    } 

    // If input equation is quadratic find roots
    else { 

        // Splitting equation on basis of sign
        String[] array = equation.split("(?=[+-])");
        for (String term : array) {
            int len = term.length();
            StringBuffer newTerm = new StringBuffer(term);

            // If term ends with x2, then delete x2 and convert remaining term into integer
            if (term.endsWith("X2") || (term.endsWith("x2"))) {
                number = newTerm.delete(len - 2, len);
                a += Integer.parseInt(number.toString());
            }
            // If term ends with x, then delete x and convert remaining term into integer
            else if (term.endsWith("X") || (term.endsWith("x"))) {
                number = newTerm.deleteCharAt(len - 1);
                b += Integer.parseInt(number.toString());
            }
            // If constant,then convert it into integer
            else {
                c += Integer.parseInt(term);
            }
        }
        // Display value of a,b,c and complete equation
        System.out.println("Coefficient of x2: " + a);
        System.out.println("Coefficient of x: " + b);
        System.out.println("Constent term: " + c);
        System.out.println("The given equation is: " + a + "x2+(" + b + ")x+(" + c + ")=0");

        // Calculate discriminant
        disc = (b * b) - (4 * a * c);
        System.out.println(" Discriminant= " + disc);

        // square root of discriminant
        sq_dis = (float) Math.sqrt(Math.abs(disc));

        // conditions to find roots

        if (disc > 0) {
            root[0] = (-b + sq_dis) / (2 * a);
            root[1] = (-b - sq_dis) / (2 * a);
            System.out.println("Roots are real and unequal");
            System.out.println("Root1= " + root[0]);
            System.out.println("Root2= " + root[1]);
        } 
        else if (disc == 0) {
            root[0] = ((-b) / (2 * a));
            System.out.println("Roots are real and equal");
            System.out.println("Root1=Root2= " + root[0]);
        } 
        else {

             root[0] = -b / (2 * a);
             root[1] = Math.abs((sq_dis) / (2 * a));

            System.out.println("Roots are complex");
            System.out.println("ROOT1= " + root[0] + "+" + root[1] + "+i");
            System.out.println("ROOT2= " + root[0] + "-" + root[1] + "+i");
        }
    }

回答by DevRocks123

Hope this helps--

希望这可以帮助 -

import java.util.Scanner;  
class QuadraticCalculator  
{   
public static void main(String args[])  
{

    Scanner s=new Scanner(System.in);  
    double a,b,c,quad_dis,quad_11,quad_1,quad_21,quad_2;  
    System.out.println("Enter the value of A");  
    a=s.nextDouble();  
    System.out.println("\nEnter the value of B");  
    b=s.nextDouble();
    System.out.println("\nEnter the value of C");
    c=s.nextDouble();
    quad_dis=b*b-4*a*c;
    quad_11=(-1*b)+(Math.sqrt(quad_dis));
    quad_1=quad_11/(2*a);
    quad_21=(-1*b)-(Math.sqrt(quad_dis));
    quad_2=quad_21/(2*a);
    int choice;
    System.out.println("\n\nWhat do you want to do with the numbers you entered ?\n(1) Calculate Discriminant\n(2) Calculate the values\n(3) Find the nature of roots\n(4) All of the above");
    choice=s.nextInt();
    switch(choice)
    {
        case 1: System.out.println("\nDiscriminant: "+quad_dis);
                break;
        case 2: System.out.println("\nValues are: "+quad_1+", "+quad_2);
                break;
        case 3: if(quad_dis>0)
                {
                    System.out.println("\nThe roots are REAL and DISTINCT");
                }
                else if(quad_dis==0)
                {
                    System.out.println("\nThe roots are REAL and EQUAL");
                }
                else
                {
                    System.out.println("\nThe roots are IMAGINARY");
                }
                break;
        case 4: System.out.println("\nDiscriminant: "+quad_dis);
                System.out.println("\nValues are: "+quad_1+", "+quad_2);
                if(quad_dis>0)
                {
                    System.out.println("\nThe roots are REAL and DISTINCT");
                }
                else if(quad_dis==0)
                {
                    System.out.println("\nThe roots are REAL and EQUAL");
                }
                else
                {
                    System.out.println("\nThe roots are IMAGINARY");
                }
                break;

    }
    System.out.println("\n\nThank You for using this Calculator");
}
}

回答by Du?an Stefanovi?

else {
    if ((Math.sqrt(-d) / (2*a)) > 0) {
        System.out.println(r + " + " + (Math.sqrt(-d) / (2*a)) + " i");
        System.out.println(r + " - " + (Math.sqrt(-d) / (2*a)) + " i");
    }
    else if ((Math.sqrt(-d) / (2*a)) == 0){
        System.out.println(r);
    }
    else {
        System.out.println(r + " - " + (Math.sqrt(-d) / (2*a)) + " i");
        System.out.println(r + " + " + (Math.sqrt(-d) / (2*a)) + " i");
    }