2017-10-18 56 views
2

因此,我已經開始使用Java創建GUI的基礎知識。我已經開始創建一個基本的數學程序,該程序將解決輸入通過選項窗格輸入的二次方程。但是,我注意到,只要沒有想象的解決方案,該計劃就會給我提供解決方案。 下面是代碼:使用javax.swing.JOptionPane輸入時的計算錯誤

package window.math; 
import javax.swing.JOptionPane; 

public class WindowMath { 

public static void Solve(double a, double b, double c){ //Gives the input of A, B, C to the formula 
    double x; 
    x = Math.pow(b,2) - 4 * a * c; //Determines whether solution will have imaginary numbers or not 
    if (x >= 0){ //Real Solution output 
     double y; 
     double z; 
     double j; 
     double k; 
     double l; 
     y = -b + Math.sqrt(x); 
     z = -b - Math.sqrt(x); 
     j= 2 * a; 
     k = y/j; 
     l = z/j; 
     JOptionPane.showMessageDialog(null, "The solutions are x = " + k + " and x = " + l + ".", "Quadratic Solver", JOptionPane.PLAIN_MESSAGE); 
    } else { //Imaginary Solution Output 
     double j; 
     double v; 
     double w; 
     double y; 
     double z; 
     y = Math.abs(x); 
     w = Math.sqrt(y); 
     j = 2 * a; 
     v = w/j; 
     z = -b/j; 
     JOptionPane.showMessageDialog(null, "The solutions are x = " + z + " + " + v + "i and x = " + z + " - " + v + "i.", "Quadratic Solver", JOptionPane.PLAIN_MESSAGE); 
    } 
} 
public static void main(String[] args) { 
    String a = JOptionPane.showInputDialog("Enter a:"); 
    String b = JOptionPane.showInputDialog("Enter b:"); 
    String c = JOptionPane.showInputDialog("Enter c:"); 
    double num1 = Double.parseDouble(a); 
    double num2 = Double.parseDouble(b); 
    double num3 = Double.parseDouble(b); 
    Solve(num1,num2,num3); 
} 

}

當我運行三個數字,讓同一個虛數的解決方案,那麼該程序工作正常。然而,對於類似a = 1,b = 2和c = 1的情況,解應該是x = -1,x = -1。只有真正的解決方相反,輸出結果給我「x = -1.0 + 1.0i,x = -1.0 - 1.0i。我目前使用NetBeans IDE 8.2(Build 201609300101)編碼並使用Java更新1.8.0_144和JavaVM 25.144-b01。幫助將不勝感激

+1

@BrenoQ我不能相信我完全忽略了這一點,非常感謝你,希望我不要再犯這個錯誤, – CurlyCue

回答

2

在你的代碼的問題是在下面的行(從main法):

double num3 = Double.parseDouble (b); 

它應該是:

double num3 = Double.parseDouble (c); 
+0

更快比我想的更多,但我完全同意:) – Sorontur