我的回归价值不是正确的,而我只是想知道我做错了什么,我的代码看起来很好?!
即将出现的一些测试是:
Test failed: expected was not equal to actual
The discriminant is not being computed correctly
Test failed: expected was not equal to actual
public class QuadraticEquation {
//coefficients
private double a;
private double b;
private double c;
// created a discriminant instance variable so it's easier to access
// rather than tying out "Math.pow(b, 2) - 4 * a * c" every time
// the discriminant is required
private double discriminant = Math.pow(b, 2) - (4 * a * c);
//constructor
public QuadraticEquation(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
//getter for A
public double getA() {
return a;
}
//getter for B
public double getB() {
return b;
}
//getter for C
public double getC() {
return c;
}
// get discriminant
// the discriminant is inside of the square root,
// and b^2 - 4ac is the expression for the discriminant
public double getDiscriminant() {
//b^2 - 4ac
return discriminant;
}
//get root0
public double getRoot0(){
if (discriminant > 0) {
return -b + Math.sqrt(discriminant) / 2*a;
}
return Double.NaN;
}
public double getRoot1() {
if (discriminant > 0) {
return -b - Math.sqrt(discriminant) / 2*a;
}
return Double.NaN;
}
}
答案 0 :(得分:5)
您在设置a
,b
和c
之前尝试计算判别式,因此它自然会出现零。< / p>
将计算判别式的行向下移动到构造函数中。
public class QuadraticEquation {
//coefficients
private double a;
private double b;
private double c;
private double discriminant;
//constructor
public QuadraticEquation(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
discriminant = b * b - (4 * a * c);
}
// etc.
另请注意,由于后者的计算方式,b * b
通常优于Math.pow(b, 2)
。
此外,getRoot0
和getRoot1
内的操作发生的顺序错误。你需要括号来做这样的事情。
public double getRoot0(){
if (discriminant > 0) {
return ( -b + Math.sqrt(discriminant)) / (2 * a);
}
return Double.NaN;
}
,同样在getRoot1
。