所以我是个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 + ")");
}
}发布于 2015-10-01 01:51:02
^ is the xor operator in java and 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.发布于 2015-10-01 01:51:38
首先,^不是一个求幂运算符,导致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.发布于 2015-10-01 02:29:07
是您的操作顺序导致您获得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;https://stackoverflow.com/questions/32872533
复制相似问题