用类解一元二次方程式
定义一个代表一元二次方程ax2+bx+c=0的类QuadraticEquation,其属性为三个系数a、b、c(均为私有属性),类中定义的方法参考main方法中的代码。main方法源码:
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
double a = Double.parseDouble(input.next());
double b = Double.parseDouble(input.next());
double c = Double.parseDouble(input.next());
if(a == 0){
System.out.println("Wrong Format");
System.exit(0);
}
//create a QuadraticEquation object
QuadraticEquation equation = new QuadraticEquation(a, b, c);
//get value of b * b - 4 * a * c
double discriminant = equation.getDiscriminant();
System.out.println("a=" + equation.getA() +
",b=" + equation.getB() +
",c=" + equation.getC()+":");
if (discriminant < 0) {
System.out.println("The equation has no roots.");
}
else if (discriminant == 0)
{
System.out.println("The root is " +
String.format("%.2f", equation.getRoot1()));
}
else // (discriminant >= 0)
{
System.out.println("The roots are " +
String.format("%.2f", equation.getRoot1())
+ " and " + String.format("%.2f", equation.getRoot2()));
}
}
}
class QuadraticEquation{
//your code
}
注意:须提交完整源码,包括Main类。
输入格式:
在一行中输入a、b、c的值,可以用一个或多个空格或回车符分开。
输出格式:
- 当输入非法时,输出“Wrong Format”
- 当有一个实根时,输出(2行):
- a=值,b=值,c=值:
- The root is 值(保留两位小数)
- 当有两个实根时,输出(2行):
- a=值,b=值,c=值:
- The roots are 值1 and 值2(均保留两位小数)
输入样例1:
在这里给出一组输入。例如:
1 84 -6653
输出样例1:
在这里给出相应的输出。例如:
a=1.0,b=84.0,c=-6653.0:
The roots are 49.74 and -133.74
输入样例2:
在这里给出一组输入。例如:
1.00 -2.000 1
输出样例2:
在这里给出相应的输出。例如:
a=1.0,b=-2.0,c=1.0:
The root is 1.00
代码如下(哈哈哈):
import java.util.Scanner;
public class Main {
private static int solveQuadratic(double x,double y,double z, double[] roots)
{// TODO 自动生成的方法存根
double a=x;
double b=y;
double c=z;
int n;
if(a!=0&&b*b-4*a*c<0)
{
n=0;
}
else if(a!=0&&b*b-4*a*c==0)
{
roots[0]=(-b+Math.sqrt(b*b-4*a*c))/(2*a);
n=1;
}
else if(a!=0&&b*b-4*a*c>0)
{
roots[0]=(-b+Math.sqrt(b*b-4*a*c))/(2*a);
roots[1]=(-b-Math.sqrt(b*b-4*a*c))/(2*a);
n=2;
}
else
{
n=-1;
}
return n;
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
double a,b,c;
Scanner input=new Scanner(System.in);
double[] roots=new double[2];
double x=input.nextDouble();
double y=input.nextDouble();
double z=input.nextDouble();
int n=solveQuadratic(x,y,z, roots);
if(n==-1)
{
System.out.println("Wrong Format");
}
else if(n==0)
{
System.out.println("The equation has no roots.");
}
else if(n==1)
{
System.out.println("a=" + x +",b=" + y + ",c=" + z+":");
System.out.printf("The root is %.2f", roots[0]);
}
else
{
System.out.println("a=" + x +",b=" + y + ",c=" + z+":");
System.out.printf("The root are %.2f and %.2f", roots[0], roots[1]);
}
}
}