二次方程式返回NaN,即使在考虑负基础时也是如此

时间:2016-07-20 14:20:13

标签: java nan quadratic square-root

这个问题适用于我的Java类简介,问题是要求我使用类来解决二次方程。

我正在尝试修复我的课程,以便它不会返回NaN。我已经使用Math.abs()来尝试修复激进下的数字是负数的任何情况,但我仍然得到NaN。这是我的课程代码:

    public class Quadratic
{
//Private data members
private double a;
private double b;
private double c;
private double posX;
private double negX;

//Deafault constructor
public void Quadratic()
{
    a = 1;
    b = 0;
    c = 0;
    posX = 0;
    negX = 0;
}

//The mutators
public void setQuad(Double alpha, double bravo, double charlie)
{
    alpha = a;
    bravo = b;
    charlie = c;
    getQuad();
}

//The accessors
public double getQuad()
{
    double temp = (Math.pow(b, 2) - (4 * a * c));//getting the number inside the root

    if(temp < 0)
        temp = Math.abs(temp);
    //ensures that the function can run until complex numbers are sorted

    posX = (-b + (Math.sqrt(temp)))/(2 * a);//calculates when added
    negX = (-b + (Math.sqrt(temp)))/(2 * a);//calculates when subtracted
//error: Keep getting NaN for answers, already accounted for negative inside the root
//       not a 0 in the descriminant.
    return 0;
}

//My toString which is what will be output at System.out.println(N)
public String toString()
{
    if(negX == posX)
        return "X = "+ negX;
    else
        return "X = "+ negX +" and "+ posX;
}
}

我的数学不正确,还是我错误地使用了数学实用程序?

1 个答案:

答案 0 :(得分:0)

  1. 您的构造将您的字段分配给构造函数中的本地参数
  2. 通常你会想要允许从构造函数中分配字段,因此我把它放在
  3. 你的negX任务与posX
  4. 相同
  5. getQuad不需要通过您的实施返回任何内容
  6. 你的访问者getQuad并不是真正的访问者,它更像是一个改变posX和negX的mutator,实现了下面的访问者
  7. 公共阶层二次方     {     私人双a;     私人双b;     私人双c;     私人双posX;     私人双重否定;

    //Default constructor
    public Quadratic()
    {
        //1.
        a = 0;
        b = 0;
        c = 0;
        posX = 0;
        negX = 0;
    }
    
    public Quadratic(double a, double b, double c){
        //2.
        this.a = a;
        this.b = b;
        this.c = c; 
        this.posX = 0;
        this.negX = 0;
    }
    
    
    //The mutators
    public void setQuad(Double alpha, double bravo, double charlie)
    {
       a = alpha;
       b = bravo;
       c = charlie;
       getQuad();
    }
    
    public void getQuad()
    {
       //4.
        double temp = (Math.pow(b, 2) - (4 * a * c));//getting the number inside the root
    
        if(temp < 0)
            temp = Math.abs(temp);
        //ensures that the function can run until complex numbers are sorted
    
        posX = (-b + (Math.sqrt(temp)))/(2 * a);
    
        //3.
        negX = (-b - (Math.sqrt(temp)))/(2 * a);
    }
    
    //Accesors  5.
    public double getA(){
        return this.a
    }
    
    public double getB(){
        return this.b
    }
    
    public double getC(){
        return this.c
    }
    //Overriding toString
    public String toString()
    {
        if(negX == posX)
            return "X = "+ negX;
        else
            return "X = "+ negX +" and "+ posX;
    }
    

    }