Java类求解⼀元⼆次⽅程的根
* Equation.java
*/
package cn.p;
/**
* 计算⼀元⼆次⽅程的根
* @author TongQiang
*
*/
public class Equation {
double a,b,c; //⽅程的系数
double x1,x2; //两个根
double r; //实部
double v; //虚部
int type; //0表⽰⼀个根,1表⽰两个实根,2表⽰两个复数的根
public Equation(double a,double b,double c){
this.a = a;
this.b = b;
this.c = c;
}
private double delta(){
记住我return b*b-4*a*c;
}
public void calculate(){
double d = delta();
if(Math.abs(d) < 1E-5){
type = 0;
x1 = -b/(2*a);
x2 = x1;
}else if(d > 0){
type = 1;
x1 = (-b+Math.sqrt(d))/(2*a);
x2 = (-b-Math.sqrt(d))/(2*a);
}else{
type = 2;
r = -b/(2*a);
v = Math.sqrt(-d)/(2*a);
}
}
public void showResult(){
switch(type){
case 0:
System.out.println("⽅程只有⼀个实根,x1=x2="+x1);
break;
case 1:
System.out.println("⽅程有两个实根,分别是:x1="+x1+"/tx2="+x2);
break;
case 2:
System.out.println("⽅程有两个复数根,分别是:"+r+"+"+v+"i,/t"+r+"-"+v+"i");
break;
}
}
public static void main(String[] args) {
Equation eq1 = new Equation(1,2,2);
eq1.calculate();
eq1.showResult();
Equation eq2 = new Equation(1,-2,1); eq2.calculate();
eq2.showResult();
Equation eq3 = new Equation(1,6,5); eq3.calculate();
eq3.showResult();
}
}
发布评论