本文主要是介绍Java语言程序设计 例题9.10(代数:二次方程式),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
*9.10 (Algebra: quadratic equations) 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
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.” See Programming Exercise 3.1 for sample runs.
*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的运行示例。
代码如下:
import java.util.Scanner;
public class Unite9Test10
{public static void main(String[] args) {Scanner input = new Scanner(System.in);System.out.println("请输入a,b,c:");double a = input.nextDouble();double b = input.nextDouble();double c = input.nextDouble();QuadraticEquation q =new QuadraticEquation(a,b,c);if(q.getRoot1()==0 && q.getRoot2()==0) {System.out.println("The equation has no roots");}else if(q.getRoot1()==q.getRoot2()) {System.out.println(q.getRoot1());}else {System.out.println("root1 = "+q.getRoot1()+","+"root2 = "+q.getRoot2());}}
}
class QuadraticEquation
{private double a;private double b;private double c;public QuadraticEquation(double a,double b,double c){this.a = a;this.b = b;this.c = c;}public double getA() {return a;}public void setA(double a) {this.a = a;}public double getB() {return b;}public void setB(double b) {this.b = b;}public double getC() {return c;}public void setC(double c) {this.c = c;}public double getDiscriminant() {return b*b - 4*a*c;}public double getRoot1() {double root1 = (-b +Math.sqrt(this.getDiscriminant()))/(2*a);if(getDiscriminant() >= 0) {return root1;}else {return 0;}}public double getRoot2() {double root2 = (-b - Math.sqrt(this.getDiscriminant()))/(2*a);if(getDiscriminant() >= 0) {return root2;}else {return 0;}}
}
结果如下:
这篇关于Java语言程序设计 例题9.10(代数:二次方程式)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!