编程求解一元二次方程ax^2 + bx + c = 0的根,要求a、b、c从键盘输入。 要求Main类中必须有如下方法:
public static void main(String[] args);//主方法
public static int solveQuadratic(double[] eqn, double[] roots);//eqn存储输入的三个系数a、b、c,然后
将两个实数根存储进roots中,该方法返回实数根的个数。
输入格式:
从键盘输入一元二次方程的三个系数的值(均为实型数),可以用一个或多个空格或回车分隔。
输出格式:
当输入数据非法时,输出“Wrong Format”
当无实数根时,输出如下字符串“The equation has no roots”;
当只有一个根时,输出如下格式“The equation has one root: 值”;(注意,输出的值必须保留四位小数,且值前面有一个空格)
当有两个根时,输入如下格式“The equation has two roots: 值1 and 值2”;(注意,输出的值必须保留四位小数,且值前面均有一个空格)
输入样例1:
在这里给出一组输入。例如:
2 6 -554
输出样例1:
在这里给出相应的输出。例如:
The equation has two roots: 15.2108 and -18.2108
输入样例2:
在这里给出一组输入。例如:
300.0 0.0 0.00
输出样例2:
在这里给出相应的输出。例如:
The equation has one root: 0.0000
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double[] arr=new double[3];
int f=1;
for (int i = 0; i < 3; i++) {
if (sc.hasNextDouble()){
arr[i]=sc.nextDouble();
}else {
f = 0;
break;
}
}
if (f==1&&arr[0]!=0){//a=0的时候,不是二次函数,应该报错数据不合法
double[] roots=new double[2];
int a=solveQuadratic(arr,roots);
if (a==0){
System.out.println("The equation has no roots");
}else if (a==1){
System.out.printf("The equation has one root: %.4f\n",roots[0]);
}else if (a==2){
System.out.printf("The equation has two roots: %.4f and %.4f\n",roots[0],roots[1]);
}
}else System.out.println("Wrong Format");
}
public static int solveQuadratic(double[] eqn, double[] roots){
int ret=0;
if (eqn[1]*eqn[1]-4*eqn[0]*eqn[2]>=0){
roots[0]=(-eqn[1]+Math.sqrt(eqn[1]*eqn[1]-4*eqn[0]*eqn[2]))/(2*eqn[0]);
roots[1]=(-eqn[1]-Math.sqrt(eqn[1]*eqn[1]-4*eqn[0]*eqn[2]))/(2*eqn[0]);
if (Math.round(roots[0])==Math.round(roots[1])) ret=1;
else ret=2;
}
return ret;
}
}