2014-05-18 101 views
-2

我試過併成功構建了一個二次方程求解器。java中的二次方程求解器

public class Solver { 
public static void main (String[] args) { 
int a = Integer.parseInt(args[0]); 
int b = Integer.parseInt(args[1]); 
int c = Integer.parseInt(args[2]); 
double positive = (-b + Math.sqrt(b*b-4*a*c))/2*a; 
double negative = (-b - Math.sqrt(b*b-4*a*c))/2*a; 
System.out.println("First answer is " + positive); 
System.out.println("Second answer is " + negative); 
} 
} 

有時我會在輸出中得到NaN。 我做錯了什麼?

+1

對於輸入什麼值? –

+3

那麼你給了什麼投入?我懷疑你給了這樣的價值觀,以至於*沒有解決方案。 (即b^2 - 4ac爲負)。 –

+2

您需要處理'a = 0'和'b * b-4 * a * c'爲負的情況。 – BobTheBuilder

回答

0

NaN表示非數字。您輸入了導致數學上未定義的操作的輸入。所以如果第一個數字「a」爲零,你會得到的,如果b * b大於4 * a * c,你也會得到這個消息,第一種情況是除以零,第二種情況是計算負數。

+0

如何防止Nan? – Rona

1

NaN - 不是數字 - 是代表無效數學運算結果的值。使用實數時,無法計算負數的平方根 - 因此返回NaN

您的解決方案的另一個問題是/2*a片段。除法和乘法具有同等重要性,因此括號是必要的。此外,如果a等於零,Java將拋出java.lang.ArithmeticException:/by zero - 您還需要檢查它。

一個可能的解決方案將是:

if (a == 0) { 
    System.out.println("Not a quadratic equation."); 
    return; 
} 

double discriminant = b*b - 4*a*c; 
if (discriminant < 0) { 
    System.out.println("Equation has no ansewer."); 
} else { 
    double positive = (-b + Math.sqrt(discriminant))/(2*a); 
    double negative = (-b - Math.sqrt(discriminant))/(2*a); 
    System.out.println("First answer is " + positive); 
    System.out.println("Second answer is " + negative); 
} 
+0

謝謝。你是否認爲第一個雙重判別? – Rona

+0

@羅娜是,這是一個錯字。 –