我的二次公式代码有什么问题

时间:2015-06-18 17:32:09

标签: quadratic

public class QuadraticEqn {
private double a, b, c;
public QuadraticEqn(double x, double y, double z){
    a=x;
    b=y;
    c=z;
}
private double disc = b*b-4*a*c;
public boolean hasSolutions(){
    if(disc>=0)
        return true;
    else
        return false;
 }
 public double getSolutions1(){
     return (-b-Math.sqrt(disc))/(2*a);
}
 public double getSolutions2(){
        return (-b+Math.sqrt(disc))/(2*a);
    }

}


import java.util.Scanner;
public class QuadraticEquationTest {

     public static void main(String[] args) {
        Scanner values = new Scanner(System.in);
        System.out.println("enter values for a, b, c:");
        double a=values.nextDouble();
        double b=values.nextDouble();
        double c=values.nextDouble();

        QuadraticEqn qe = new QuadraticEqn(a, b, c);
        if (qe.hasSolutions())
        System.out.println(qe.getSolutions1()+"  "+qe.getSolutions2());
        else
         System.out.println("No real solutions");
    }

}

主类应该打印出给定输入的实际解决方案。几个小时以来我一直坚持这个问题。我似乎无法弄清楚我做错了什么。我一直得到错误的答案。求救!

1 个答案:

答案 0 :(得分:0)

您遇到了

的问题

private double disc = (b*b)-(4*a*c);

当您QuadraticEqn时,变量disc被赋予一个值,但是,在您保存a,b和c之前,它会被赋予一个值。因此它创建disc,就好像a,b和c都是0。

要解决此问题,请在构造函数中更新disc

public class QuadraticEqn {
   private double a, b, c, disc; //We're created before the constructor 
                                 //runs with default values of 0!
   public QuadraticEqn(double x, double y, double z){
       a=x;
       b=y;
       c=z;
       disc = b*b-4*a*c; //Give me a value after we know what the others are!
   }

   public boolean hasSolutions(){
     if(disc>=0)
         return true;
     else
         return false;
   }

   public double getSolutions1(){
      return (-b-Math.sqrt(disc))/(2*a);
   }

   public double getSolutions2(){
      return (-b+Math.sqrt(disc))/(2*a);
   }

}