二次公式NaN

时间:2014-10-25 22:15:07

标签: java

我正试图找到这个程序的二次方程式,我不确定我犯了哪个错误,但似乎它对我不起作用。对于输入(5,-8,3),(3,2,-7),输出为“NaN”。请记住,我有另一个类来测试这些方法,如有必要,我可以发布。

编辑代码:

import java.util.Scanner; 
import static java.lang.System.*;
import static java.lang.Math.*;

public class Quadratic
{
    private int a, b, c;
    private double rootOne;
    private double rootTwo;

    public Quadratic()
    {

    }

    public Quadratic(int quadA, int quadB, int quadC)
    {
        a = quadA;
        b = quadB;
        c = quadC;
    }

    public void setEquation(int quadA, int quadB, int quadC)
    {
        a = quadA;
        b = quadB;
        c = quadC;
    }

    public void calcRoots( )
    {
        rootOne = (-b + Math.sqrt(Math.pow(b,2)-4*a*c))/(2*a);
        rootTwo = (-b - Math.sqrt(Math.pow(b,2)-4*a*c))/(2*a);
    }

    public void print( )
    {
        System.out.println("");
        System.out.print("ROOTS :: "+ rootOne);
        System.out.println("\t" + rootTwo);
        System.out.println("");
        System.out.println("");
    }
}

TEST CLASS:

import java.util.Scanner; 
import static java.lang.System.*;
import static java.lang.Math.*;

public class QuadraticRunner
{
    public static void main( String[] args )
   {
        Scanner keyboard = new Scanner(in);

        System.out.print("ENTER A :: ");
        int a = keyboard.nextInt();

        System.out.print("ENTER B :: ");
        int b = keyboard.nextInt();

        System.out.print("ENTER C :: ");
        int c = keyboard.nextInt();

        Quadratic test = new Quadratic();
        test.calcRoots();
        test.print();


        System.out.print("ENTER A :: ");
        a = keyboard.nextInt();

        System.out.print("ENTER B :: ");
        b = keyboard.nextInt();

        System.out.print("ENTER C :: ");
        c = keyboard.nextInt();

        test.calcRoots();
        test.print();


        System.out.print("ENTER A :: ");
        a = keyboard.nextInt();

        System.out.print("ENTER B :: ");
        b = keyboard.nextInt();

        System.out.print("ENTER C :: ");
        c = keyboard.nextInt();

        test.calcRoots();
        test.print();
   }
}

3 个答案:

答案 0 :(得分:2)

你错过了括号。

rootOne = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);

此外,您还没有处理任何特殊情况,如虚根,重复根等。

答案 1 :(得分:1)

我不会使用setEquation()方法和实例变量。我认为这可能会让你陷入不必要的麻烦。

您可以这样做,而无需存储实例变量:

public double [] calcRoots(int a, int b, int c)
{
    double[] roots = new double[2];

    roots[0] = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a);
    roots[1] = (-b - Math.sqrt(b * b - 4 * a * c)) / (2 * a);

    return roots;
}

答案 2 :(得分:1)

在测试中,您实际上从未实际设置abc。您使用无参数的Quadratic构造函数:

Quadratic test = new Quadratic();

你不打电话给setEquation

abc的默认值为0,因此这就是您获得NaN(“非数字”)值的原因:

( -0 + Math.sqrt( Math.pow( 0 , 2 ) - 4 * 0 * 0 ) ) / ( 2 * 0 )
    ==
( 0.0 ) / ( 0.0 ) // IEEE division of zero by zero results in NaN

使用(int, int, int)构造函数或setEquation

Quadratic test = new Quadratic(a, b, c);
test.setEquation(a, b, c);