1

到目前为止我有这段代码,但是每次我运行并将三个数字放入一个 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);


     } 
   }
4

4 回答 4

4

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

输入三个系数
1 
5 
6
根 1 是:-2.0
根 2 是:-3.0

如果您也想考虑非实根,您可以执行类似的操作

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");
}
于 2013-01-17T23:06:30.660 回答
0

希望这可以帮助 -

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");
}
}
于 2014-04-13T09:58:44.300 回答
0

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

公共静态无效主要(字符串[]参数){

    // 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");
        }
    }
于 2018-04-23T16:25:50.437 回答
-1
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");
    }
于 2016-01-08T19:53:36.673 回答