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

Kha*_*nak 1 java applet computer-science

求解二次方程

到目前为止,我已写下以下内容.我不确定如何引入第二种方法

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

}
Run Code Online (Sandbox Code Playgroud)

apn*_*ton 5

首先,你的代码将无法编译 - 你}在开始之后还有一个额外的代码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!
}
Run Code Online (Sandbox Code Playgroud)