java二次公式返回NaN,即使考虑了负根
这个问题是关于Java类的介绍,这个问题要求我使用类来解一个二次方程
我正在尝试修复我的类,以便它不会返回NaN。我已经用Math.abs()
来尝试修复任何情况,其中根下的数字是负数,但我仍然得到NaN。以下是我的课程代码:
public class Quadratic
{
//Private data members
private double a;
private double b;
private double c;
private double posX;
private double negX;
//Deafault constructor
public void Quadratic()
{
a = 1;
b = 0;
c = 0;
posX = 0;
negX = 0;
}
//The mutators
public void setQuad(Double alpha, double bravo, double charlie)
{
alpha = a;
bravo = b;
charlie = c;
getQuad();
}
//The accessors
public double getQuad()
{
double temp = (Math.pow(b, 2) - (4 * a * c));//getting the number inside the root
if(temp < 0)
temp = Math.abs(temp);
//ensures that the function can run until complex numbers are sorted
posX = (-b + (Math.sqrt(temp)))/(2 * a);//calculates when added
negX = (-b + (Math.sqrt(temp)))/(2 * a);//calculates when subtracted
//error: Keep getting NaN for answers, already accounted for negative inside the root
// not a 0 in the descriminant.
return 0;
}
//My toString which is what will be output at System.out.println(N)
public String toString()
{
if(negX == posX)
return "X = "+ negX;
else
return "X = "+ negX +" and "+ posX;
}
}
是我的数学不正确,还是我使用的数学工具不正确
# 1 楼答案
公共类二次型 { 私人双a; 私人双b; 私人双c; 私有双posX; 私人双负
}