Java 二次公式程序-获取NaN误差

Java 二次公式程序-获取NaN误差,java,nan,quadratic,Java,Nan,Quadratic,我不确定我的代码哪里做错了,但我无法让它正常运行…测试人员不断返回NaN,而不是预期的结果。本练习的目标是打印二次方程的所有实解。溶液1应返回较小的溶液,溶液2应返回较小的溶液。这是我的课 public class QuadraticEquation { private int a; private int b; private int c; private boolean hasSolutions; private double discri

我不确定我的代码哪里做错了,但我无法让它正常运行…测试人员不断返回NaN,而不是预期的结果。本练习的目标是打印二次方程的所有实解。溶液1应返回较小的溶液,溶液2应返回较小的溶液。这是我的课

   public class QuadraticEquation
   {
    private int a;
    private int b;
    private int c;
    private boolean hasSolutions;
    private double discriminant = (b * b) - (4 * a * c);
    private double solution1;
    private double solution2;
   /**
 * Constructs a quadratic equation
 * @param a coefficient a 
 * @param b coefficient b
 * @param c coefficient c
 */

    public QuadraticEquation(int a, int b, int c)
    {
        a = a;
        b = b;
        c = c;
    }
     /**
 * Checks if there is a solution
 * @return true if there is a real solution
 */

    public boolean hasSolutions()
    {
        if(discriminant < 0)
            hasSolutions = false;
        else
            hasSolutions = true;
        return hasSolutions;
    }
    /**
  * Returns first solution
  * @return first solution
  */

    public double getSolution1()
    {
        if(hasSolutions)
        {
            if((-b + Math.sqrt(discriminant) / (2 * a)) < (-b - Math.sqrt(discriminant) / (2 * a)))
                solution1 = (-b + Math.sqrt(discriminant) / (2 * a));
            else
                solution1 = (-b - Math.sqrt(discriminant) / (2 * a));
        }
            return solution1;
    }
    /**
    * Returns second solution
    * @return second solution
    */  

    public double getSolution2()
    {
        if(hasSolutions)
        {
            if((-b + Math.sqrt(discriminant) / (2 * a)) > (-b - Math.sqrt(discriminant) / (2 * a)))
                solution2 = (-b + Math.sqrt(discriminant) / (2 * a));
            else
                solution2 = (-b - Math.sqrt(discriminant) / (2 * a));
        }
            return solution2;
    }

  }
非常感谢!:)

  • 您正在类上下文的对象初始化部分中计算
    判别式
    ,该类上下文使用默认值
    a、b和c
    计算。在初始化
    a、b
    c

  • 您正在构造函数方法中隐藏变量,因为
    a、b、c
    是参数字段。使用此:

    public QuadraticEquation(int a, int b, int c)
    {
      this.a = a;
      this.b = b;
      this.c = c;
    }
    
  • NaN
    是浮点计算的结果,其操作类似于将零除以零。因此,如果在上述修复中仍然发生这种情况,请找出原因


  • 它是否为
    hasSolutions()
    输出
    true
    ?是的,但它应该返回false:(谢谢!它可以工作,只是它不返回两个解;它只返回较小的解,第二个解返回true。正如这个答案所建议的,在构造函数中计算
    判别式,第二个不应该返回true。
    
    public QuadraticEquation(int a, int b, int c)
    {
      this.a = a;
      this.b = b;
      this.c = c;
    }