二次方程式 returns NaN,即使考虑到负根

Quadratic Formula returns NaN, even when negative radical is accounted for

这道题是关于 Java class 的介绍,题目要求我使用 classes 求解二次方程。

我正在尝试修复我的 class 以便它不会 return NaN。我已经使用 Math.abs() 尝试修复部首下的数字为负数的任何情况,但我仍然得到 NaN。这是我的 class:

代码
    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. 您的构造正在将您的字段分配给构造函数中的局部参数
  2. 通常你会希望允许从构造函数中分配字段的能力,因此我在其中放了一个
  3. 您的 negX 分配与 posX 相同
  4. getQuad 不需要return任何与您的实施
  5. 你的访问器 getQuad 并不是一个真正的访问器,它更像是一个改变 posX 和 negX 的修改器,实现了下面的访问器

public class 二次方 { 私人双人间; 私人双人间; 私人双人间; 私人双posX; 私人双 negX;

//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;
}

}