簡體   English   中英

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

[英]Create a java program to solve quadratic eqations

求解二次方程

程序必須有兩種方法quadraticEquationRoot1()以輸入3個double s表示abc並返回兩個根中較大的a ,並且quadraticEquationRoot2()以輸入3個double s表示輸入abc (按該順序)並返回兩個根中較小的根。

我們假設選擇了數字abc ,使得平方根永遠不會是負數的平方根

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

public class MathUtilities
{
    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)(){
            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.min(root1, root2);  
        }
    }

如果確實需要兩種方法,則第二種方法將返回Math.min(root1, root) ,其他所有條件都相同。

就個人而言,我寧願有一個返回雙精度數組( double[] )或包含兩個根的類的方法。 在沒有充分理由的情況下,似乎很愚蠢地兩次執行了return語句之前的所有工作。

代碼很簡單:

public static double quadraticEquationRoot1(int a, int b, int c){
    double root1 = (-b + Math.pow( b*b - 2*a*c, .5 ))/(2*a);
    double root2 = (-b - Math.pow( b*b - 2*a*c, .5 ))/(2*a);
    //we have options here, use min/max, or use if statements, for example. With ifs:
    if ( root1 > root2 ){
        return root1;
    }
    return root2;
    //otherwise: return max( root1, root2 );
}

方法方法幾乎完全相同:

public static double quadraticEquationRoot2(int a, int b, int c){
    double root1 = (-b + Math.pow( b*b - 2*a*c , .5))/(2*a);
    double root2 = (-b - Math.pow( b*b - 2*a*c , .5))/(2*a);
    //we have options here, use min/max, or use if statements, for example. With ifs:
    if ( root1 < root2 ){
        return root1;
    }
    return root2;
    //otherwise: return min( root1, root2 );
}

請注意,兩種方法都只覆蓋一個根的情況

暫無
暫無

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

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