所以我是新來的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 + ")");
}
}
我很困惑。輸出「(4.42,7.42)和(3.57,.57)」,還是輸出「(南,南)」? – Kevin
哦等,輸出結果是(南,南) –
'^'不是Java中的指數運算符。 'z^2'不是你想象的那樣。 – azurefrog