Q8 二元一次方程组练习

本文介绍了一个名为QuadraticEquation的Java类,用于表示二次方程并计算其根。类中包含私有数据字段a、b、c,构造函数,以及获取系数的方法。getDiscriminant()方法返回判别式,getRoot1()和getRoot2()方法根据判别式计算根。测试程序演示了如何获取用户输入并根据判别式的值显示相应结果。
摘要由CSDN通过智能技术生成

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 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值