我在学校用java工作,到目前为止,我在处理类(class)和家庭作业问题上遇到了一些麻烦。我对二次方程类有以下标准:
到目前为止我已经:
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;
}
}
这个方程不起作用,我什至认为我不符合标准,但我不完全理解这本书的要求。有人可以帮忙吗?
最佳答案
您的数学方程的实现是正确的,但您必须放入括号中。例如;
double root1 = (-coefB + Math.sqrt(getDiscriminant()))/ 2 * coefA;
这里(-coefB + Math.sqrt(getDiscriminant()))
方程除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;
}
更详细地讲,运算符优先级表;
Operators Precedence Associativity
postfix increment and decrement ++ -- left to right
prefix increment and decrement, and unary ++ -- + - ~ ! right to left
multiplicative * / % left to right
additive + - left to right
关于java - 一元二次方程 Java 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52412129/