创建一个java程序来解决二次方程

时间:2013-06-02 23:52:42

标签: java math coding-style computer-science

求解二次方程

该计划必须有两个方法quadraticEquationRoot1(),其中输入3 double s,代表abc并返回较大的两个根和quadraticEquationRoot2()以3 double为输入,代表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);  
        }
    }

2 个答案:

答案 0 :(得分:1)

如果你真的需要两个方法,第二个方法将返回Math.min(root1, root),其他一切都是相同的。

就个人而言,我宁愿有一个方法返回一个双数组(double[])或一个包含两个根的类。在没有正当理由的情况下两次返回声明之前,似乎很难完成所有的工作。

答案 1 :(得分:0)

代码很简单:

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 );
}

请注意,通过任一方法

覆盖了只有一个根的情况