2015-09-30 3 views
3

Итак, я новичок в Java, и у меня есть задание сделать для класса, но я застрял. Предполагается, что класс должен найти пересечение двух линий, используя квадратичное уравнение. Мне сказали, что у меня есть определенные входные данные для класса, поэтому d = 5, f = -3, g = 2, m = 1 и b = 3, а два пересечения должны быть (1,4) и (-.20, 2.8). Проблема, с которой я сталкиваюсь, заключается в том, что вывод возвращает (NaN, NaN) и (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 + ")"); 
} 
} 
+2

Я смущен. Является ли вывод '(4.42.7.42) и (3.57, .57)', или является выходом '(Nan, Nan)'? – Kevin

+0

oh wait, выход (Nan, Nan) –

+3

'^' не является оператором экспоненты в Java. 'z^2' - это не то, что вы думаете. – azurefrog

ответ

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

Прежде всего^не является оператором экспоненцирование, что вызывает 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. 
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;