我不确定我在我的代码中做错了什么但我无法让它正常运行...测试人员不断返回NaN而不是预期的。本练习的目标是将所有实际解决方案打印到二次方程中。 solution1应该返回较小的解决方案,而solution2应该返回较小的解决方案。这是我的课。
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;
}
}
这是我的测试员:
public class QuadraticEquationTester
{
public static void main(String[] args)
{
QuadraticEquation equation = new QuadraticEquation(2, 2, -4);
System.out.println(equation.hasSolutions());
System.out.println("Expected: true");
System.out.println(equation.getSolution1());
System.out.println("Expected: -2");
System.out.println(equation.getSolution2());
System.out.println("Expected: 1");
QuadraticEquation equation2 = new QuadraticEquation(2, 2, 4);
System.out.println("\n" + equation2.hasSolutions());
System.out.println("Expected: false");
System.out.println(equation2.getSolution1());
System.out.println("Expected: 0");
System.out.println(equation2.getSolution2());
System.out.println("Expected: 0");
}
}
非常感谢你! :)
答案 0 :(得分:7)
您正在使用默认值discriminant
计算的类上下文的对象初始化部分中计算a, b, and c
。在初始化a,b
和c
您在构造函数方法中隐藏变量,因为a, b, c
是参数字段。使用this
:
public QuadraticEquation(int a, int b, int c)
{
this.a = a;
this.b = b;
this.c = c;
}
NaN
导致浮点计算,其操作类似于将零除零。所以,如果上述修复仍然发生这种情况,那就找出来了。