Q8问题描述:
Q8 Design a class named QuadraticEquation for a quadratic equation ax2 + bx + x = 0. The class contains:
- Private data fields a, b, and c that represent three coefficients.
- A constructor for the arguments for a, b, and c .
- Three getter methods for a, b, and c .
- A method named getDiscriminant() that returns the discriminant, which is b2 - 4ac.
- The methods named getRoot1() and getRoot2() for returning two roots of the equation
r 1 = (-b + square root of (b2 - 4ac))/2a r 2 = (-b - square root of (b2 - 4ac))/2a
These methods are useful only if the discriminant is nonnegative. Let these methods return 0 if the discriminant is negative. Draw the UML diagram for the class and then implement the class. Write a test program that prompts the user to enter values for a, b, and c and displays the result based on the discriminant. If the discriminant is positive, display the two roots. If the discriminant is 0, display the one root. Otherwise, display “The equation has no roots.”
public class QuadraticEquation {
double a;
double b;
double c;
QuadraticEquation(double a,double b,double c){
this.a=a;
this.b=b;
this.c=c;
}
public double getA() {
return a;
}
public double getB() {
return b;
}
public double getC() {
return c;
}
public double getDiscriminant(){
double r = b*b-4*a*c;
if(r>=0) return r;
else return 0;
}
public double getRoot1(){
double r = (-b + Math.sqrt(b*b - 4*a*c))/2*a;
return r;
}
public double getRoot2(){
double r = (-b - Math.sqrt(b*b - 4*a*c))/2*a;
return r;
}
}
import java.util.*;
public class Test {
public static void main(String args[]){
double a=0;
double b=0;
double c=0;
System.out.println("Please enter three elements:");
Scanner in = new Scanner (System.in);
a=in.nextDouble();
b=in.nextDouble();
c=in.nextDouble();
QuadraticEquation q = new QuadraticEquation(a,b,c);
System.out.println(q.getA());
double r = q.getDiscriminant();
System.out.println(r);
if(r>=0) System.out.println(q.getRoot1()+" "+q.getRoot2());
else if(r==0) System.out.println(q.getRoot1());
else System.out.println("The equation has no roots.");
}
}
测试数据:
Please enter three elements:
1 5 3
1.0
13.0
-0.6972243622680054 -4.302775637731995
Please enter three elements:
5 8 2
5.0
24.0
-7.752551286084111 -32.24744871391589