第九章第十题(代数:二次方程式)(Algebra: quadratic equation)
-
*9.10(代数:二次方程式)为二次方程式 设计一个名为QuadraticEquation的类。这个类包括:
- 代表三个系数的私有数据域a、b和c。
- 一个参数为a、b和c的构造方法。
- a、b、c的三个获取方法
- 一个名为getDiscriminant()的方法返回判别式b2-4ac。
- 名为getRoot1()和getRoot2()的方法返回灯饰的两个根:
这些方法只有在判别式为非负数时才有用。如果判别式为负,这些方法返回0.
画出该类的UML图并实现这个类。编写一个测试程序,提示用户输入a、b和c的值,然后显示判别式的结果。如果判别式为整数,显示两个根;如果判别式为0,显示一个根;否则,显示“The equation has no roots”.参见编程练习题3.1的运行示例。
*9.10(Algebra: quadratic equation)It is a quadratic equationDesign a class called quatraticequation. This class includes:- The private data fields a, B and C represent the three coefficients.
- A construction method with parameters a, B and C.
- Three acquisition methods of a, B and C
- A method called getdiscriminator() returns the discriminant b2-4ac.
- Methods named getroot1() and getroot2() return the two roots of the lighting:
These methods are only useful when the discriminant is nonnegative. If the discriminant is negative, these methods return 0
Draw the UML diagram of the class and implement the class. Write a test program to prompt the user to input the values of a, B and C, and then display the results of the discriminant. If the discriminant is an integer, two roots will be displayed; if the discriminant is 0, one root will be displayed; otherwise, “the equation has no roots” will be displayed. See the running example of programming exercise 3.1. -
参考代码:
package chapter09;
public class Code_10 {
public static void main(String[] args){
QuadraticEquation expr = new QuadraticEquation(1,4,4);
if(expr.getRoot1() == 0 && expr.getRoot2() == 0){
System.out.println("The equation has no roots");
}
else if(expr.getRoot1() == expr.getRoot2())
System.out.println("R : " + expr.getRoot1());
else
System.out.println("R1 : " + expr.getRoot1() + " " + "R2 :" + expr.getRoot2());
}
}
class QuadraticEquation{
private double a,b,c;
QuadraticEquation(double x, double y, double z){
a = x;
b = y;
c = z;
}
public double getA(){
return a;
}
public double getB(){
return b;
}
public double getC(){
return c;
}
public double getDiscriminant(){
return b*b - 4*a*c;
}
public double getRoot1(){
double judge = this.getDiscriminant();
if(judge >= 0){
return (-b + Math.sqrt(judge))/(2*a);
}
else
return 0;
}
public double getRoot2(){
double judge = this.getDiscriminant();
if(judge >= 0){
return (-b + Math.sqrt(judge))/(2*a);
}
else
return 0;
}
}
- 结果显示:
R : -2.0
Process finished with exit code 0