二次方程式Java类

时间:2018-09-19 18:28:25

标签: java class quadratic

我正在用Java在学校里上课,到目前为止,我在解决课堂问题和他们的作业问题时遇到了一些麻烦。对于二次方程类,我具有以下条件:

Homework Problem Here

到目前为止,我有:

private static double coefA;
private static double coefB;
private static double coefC;


public static void main(String[] args) 
{
    Scanner input = new Scanner(System.in);
    System.out.println("Please enter the a, b and c for a Quadratic: ");
    coefA = input.nextDouble();
    coefB = input.nextDouble();
    coefC = input.nextDouble();

    double discriminant = getDiscriminant();

    if (discriminant < 0)
    {
        System.out.println("There are no real roots.");

    }
    else if (discriminant == 0)
    {
        System.out.println("The one root is: "+getRoot1());
    }
    else
    {
        System.out.println("The first root is: "+getRoot1());
        System.out.println("The second root is: "+getRoot2());
    }

}
//Construct
public QuadraticEquation(double a, double b, double c)
{
    coefA = a;
    coefB = b;
    coefC = c;
}

private static double getDiscriminant()
{
    double discriminant = (coefB * coefB) - (4 * coefA * coefC);
    return discriminant;
}
static double getRoot1()
{
    double root1 = (-coefB + Math.sqrt(getDiscriminant()))/ 2 * coefA;
    return root1;

}
static double getRoot2()
{
    double root2 = (-coefB - Math.sqrt(getDiscriminant()))/ 2 * coefA;
    return root2;

}
}

等式不起作用,我什至不认为我符合标准,但我不完全理解书中的要求。有人可以协助吗?

2 个答案:

答案 0 :(得分:1)

您的数学方程式的实现是正确的,但您必须放在方括号中。例如;

double root1 = (-coefB + Math.sqrt(getDiscriminant()))/ 2 * coefA;

此处(-coefB + Math.sqrt(getDiscriminant()))方程式被{strong>除以{strong}除{strong}。之后与2进行乘法。小心点。通过此示例更改您的逻辑;

coefA

因此将其应用于其他字段以获得正确的结果。

您应该更改两种方法。

double root1 = (-coefB + Math.sqrt(getDiscriminant()))/ (2 * coefA);

更详细地讲,运算符优先级表;

static double getRoot1()
{
    double root1 = (-coefB + Math.sqrt(getDiscriminant()))/ (2 * coefA);
    return root1;

}
static double getRoot2()
{
    double root2 = (-coefB - Math.sqrt(getDiscriminant()))/ (2 * coefA);
    return root2;

}

答案 1 :(得分:0)

对于QuadraticEquation类,这不是一个好的设计。这三个变量(coefA,coefB,coefC)应该是实例变量,而不是静态变量。您应该具有一个将三个值用作输入的构造函数。对于构造函数而言,调用getDiscriminant()并计算两个可能的答案,然后使用getter检索它们,效率更高。