1

私はこれまでのところこのコードを持っていますが、実行して3つの数字をget the roots are 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、根は虚数部を持ち、返されます。ただし、これは次のような係数に対して機能します。NaNMath.sqrtNaNb*b - 4*a*c >= 0

3 つの係数を入力してください
1 
5 
6
roots1 は次のとおりです: -2.0
roots2 は: -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

次のコードを使用できます。まず、入力方程式が 2 次かどうかをチェックします。また、入力方程式が 2 次の場合、根が見つかります。このコードは複雑な根も見つけることができます。

public static void main(String[] 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");
        }
    }
于 2018-04-23T16:25:50.437 に答える