ch3_1.java

来自「java代码100例子」· Java 代码 · 共 85 行

JAVA
85
字号
//Equation.java
//ch3_1 
import java.math.*;

class ComplexRoot{
	double a,b,disc;
	public ComplexRoot(double a,double b,double disc)
	{this.a=a;
		this.b=b;
		this.disc=disc;
	}
	void Print(){
		double real=-b/(2*a);
		double image=Math.sqrt(-disc)/(2*a);
		System.out.println("complex root:"+real+"+"+image+"i,"+real+"-"+image+"i");
	}
}
class RealRoot{
	double a,b,disc;
	RealRoot(double a,double b,double disc)
	{
		this.a=a;
		this.b=b;
		this.disc=disc;
	}
	void Print()
	{
System.out.println("two real root:"+((-b+Math.sqrt(disc))/(2*a))+
","+((-b-Math.sqrt(disc))/(2*a)));
	}
}
class OneRoot{
	double a,b;
	public OneRoot(double a,double b)
	{
		this.a=a; this.b=b;
	}
	void Print()
	{System.out.println("one root:"+(-b/(2*a)));
	}
}
 class Equation
{
	double a,b,c;
	Equation(double a,double b,double c)
	{
		this.a=a;
		this.b=b;
		this.c=c;
	}
void Solve()
	{
		double disc=b*b-4*a*c;
		if(Math.abs(disc)<1E-6){
			OneRoot o=new OneRoot(a,b);
			o.Print();
		}
		else if(disc>1E-6){
			RealRoot r=new RealRoot(a,b,disc);
			r.Print();
		}
else{
			ComplexRoot c=new ComplexRoot(a,b,disc);
			c.Print();
		}
	}
}

//ch3_1.java
public class ch3_1
{
	public static void main(String[] args)
    {
		Equation e=new Equation(1,2,1);
		e.Solve();
		Equation e1=new Equation(2,2,1);
		e1.Solve();
		Equation e2=new Equation(1,5,1);
		e2.Solve();
	}
}



⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?