簡體   English   中英

創建一個Java程序來求解二次方程

[英]Create a java program to solve quadratic equations

求解二次方程

到目前為止,我已經寫下了以下內容。 我不確定如何介紹第二種方法

public static void main(string args[]){

}

public static  double quadraticEquationRoot1(int a, int b, int c) (){

}

if(Math.sqrt(Math.pow(b, 2) - 4*a*c) == 0)
{
    return -b/(2*a);
} else {
    int root1, root2;
    root1 = (-b + Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a);
    root2 = (-b - Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a);
    return Math.max(root1, root2);  
}

}

首先,您的代碼將無法編譯-在public static double quadraticEquationRoot1(int a, int b, int c) ()開始之后,您需要額外的}

其次,您沒有在尋找正確的輸入類型。 如果要輸入double類型的輸入,請確保適當地聲明該方法。 當它們可能是雙精度時,也要小心地將它們聲明為int (例如, root1root2 )。

第三,我不知道為什么會有if/else塊-最好直接跳過它,而只使用else部分中當前的代碼。

最后,要解決您的原始問題:只需創建一個單獨的方法,然后使用Math.min()代替Math.max()

因此,回顧一下代碼:

public static void main(string args[]){

}

//Note that the inputs are now declared as doubles.
public static  double quadraticEquationRoot1(double a, double b, double c) (){    
    double root1, root2; //This is now a double, too.
    root1 = (-b + Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a);
    root2 = (-b - Math.sqrt(Math.pow(b, 2) - 4*a*c)) / (2*a);
    return Math.max(root1, root2);  
}

public static double quadraticEquationRoot2(double a, double b, double c) (){    
    //Basically the same as the other method, but use Math.min() instead!
}

那么,為什么不嘗試使用相同的精確算法,卻在return語句中使用Math.min?

另外,請注意,在第一個if語句中,沒有考慮$ b $是否為負。 換句話說,您只返回$ -b / 2a $,但不檢查$ b $是否為負數,如果不是,則實際上這是兩個根中的較小者而不是較大根。 對於那個很抱歉! 我誤解了xD發生了什么

package QuadraticEquation;

import javax.swing.*;

public class QuadraticEquation {
   public static void main(String[] args) {
      String a = JOptionPane.showInputDialog(" Enter operand a :  ");
      double aa = Double.parseDouble(a);
      String b = JOptionPane.showInputDialog(" Enter operand b :  ");
      double bb = Double.parseDouble(b);
      String c = JOptionPane.showInputDialog(" Enter operand c :  ");
      double cc = Double.parseDouble(c);
      double temp = Math.sqrt(bb * bb - 4 * aa * cc);
      double r1 = ( -bb + temp) / (2*aa);
      double r2 = ( -bb -temp) / (2*aa);
      if (temp > 0) {
            JOptionPane.showMessageDialog(null, "the equation has two real roots" +"\n"+" the roots are : "+  r1+" and " +r2);

        }
      else if(temp ==0) {
            JOptionPane.showMessageDialog(null, "the equation has one root"+  "\n"+ " The root is :  " +(-bb /2 * aa));

        }

      else{

            JOptionPane.showMessageDialog(null, "the equation has no real roots !!!");
        }
    }        
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM