为什么输出(Nan,Nan)?

时间:2015-09-30 17:43:11

标签: java math integer

所以我是Java的新手,我有一个为课堂做的任务,但是我被困住了。该类应该使用二次方程找到两条线的交点。我被告知有类的具体输入,所以d = 5,f = -3,g = 2,m = 1和b = 3,两个交叉点应该是(1,4)和(-.20, 2.8)。我遇到的问题是输出返回(NaN,NaN)和(NaN,NaN)而不是正确的答案。我的代码是否有任何问题让我得到这个答案?

public class Intersect{
public static void main(String args[]){

    //prompt user for parabola vars d f g
    System.out.println("Enter the constant d:");
    int d = IO.readInt();
    System.out.println("Enter the constant f:");
    int f = IO.readInt();
    System.out.println("Enter the constant g:");
    int g = IO.readInt();

    // y = dx^2 + fx + g

    //promt user for line vars m b 
    System.out.println("Enter the constant m:");
    int m = IO.readInt();
    System.out.println("Enter the constant b:");
    int b = IO.readInt();

    // y = mx + b

    //compute intersection
    // dx^2 + fx + g = mx + b 
    // x^2 * (d) + x * (f-m) + (g-b) = 0 

    int a = d;
    int z = (f-m);
    int c = (g-b);

    double x1 = -z + (Math.sqrt (z^2 - 4 * a * c) / (2 * a));
    double x2 = -z - (Math.sqrt (z^2 - 4 * a * c) / (2 * a));
    double y1 = m * x1 + b;
    double y2 = m * x2 - b;

    //output each intersection on its own line, System.out.println() is ok for this answer submission
    System.out.println("The intersection(s) are:");
    System.out.println("(" + x1 + "," + y1 + ")");
    System.out.println("(" + x2 + "," + y2 + ")");
}
}

3 个答案:

答案 0 :(得分:4)

^ is the xor operator in java and not the exponentiation operator。因此,表达式z ^ 2 - 4 * a * c计算出负面的东西。

根据您提供的输入z = -4, a = 5, c = -1。该表达式转换为-4 ^ 2 - 4 * 5 * -1。请注意,*+有一个higher precedence than ^,即评估顺序为(-4 ^ (2 - ((4 * 5) * -1))) = -22

然后你试图找到-22的平方根,根据Math.sqrt(),它是NaN

使用Math.pow(z, 2),或者只使用z * z代替:

Math.sqrt(z * z - 4 * a * c);  // Note: This time operator precedence works,
                               // But you should use parentheses wherever
                               // the expression seems ambiguous.

答案 1 :(得分:1)

首先,^不是取幂运算符,导致Nan的原因是您将负参数传递给Math.sqrt。

来自java引用(http://docs.oracle.com/javase/7/docs/api/java/lang/Math.html):

public static double sqrt(double a)
Returns the correctly rounded positive square root of a double value.     Special cases:
If the argument is NaN or less than zero, then the result is NaN.
If the argument is positive infinity, then the result is positive infinity.
If the argument is positive zero or negative zero, then the result is the same as the argument.
Otherwise, the result is the double value closest to the true mathematical square root of the argument value.
Parameters:
a - a value.
Returns:
the positive square root of a. If the argument is NaN or less than zero, the result is NaN.

答案 2 :(得分:0)

您的操作顺序导致您获得NaN结果。 试试这个(为方便起见,添加了变量):

int a = d;
int z = f - m;
int negZ = -z;
int c = g - b;

double sq = Math.sqrt((z * z) - (4 * a * c));
double a2 = 2 * a;
double x1 = (negZ + sq) / a2;
double x2 = (negZ - sq) / a2;
double y1 = (m * x1) + b;
double y2 = (m * x2) - b;