📄 thirddegreeequation.java
字号:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */package 命令行解一元三次方程;import java.math.*;import java.io.*;/** * * @author liuwei */public class ThirdDegreeEquation {private double a,b,c,d;private double A,B;private double p,q,m;//(x+m)^3+p(x+m)+q=0private double f,g;//a*(x-x1)(x^2+f*x+g)=0private double x1,x2,x3;private int flag;public ThirdDegreeEquation(double a1,double b1,double c1,double d1){ a=a1;b=b1;c=c1;d=d1;}public void calculateRoots(){ if(a!=0) { m=b/3/a; p=b*b/3/a/a-c/a; q=m*m*m-p*m-d/a; A=-1*q/2-Math.pow((Math.pow(q/2,2)+Math.pow(p/3,3)),0.5); B=-1*q/2+Math.pow((Math.pow(q/2,2)+Math.pow(p/3,3)),0.5); double A1,B1; if (A<=0) A1=-1*Math.pow(-1*A,1.0/3); else A1=Math.pow(A,1.0/3); if (B<=0) B1=-1*Math.pow(-1*B,1.0/3); else B1=Math.pow(B,1.0/3); x1=A1+B1-b/3/a; f=b/a+x1; g=c/a+f*x1; double delta=f*f-4*g; if(delta>=0) { x2=(-1*f+Math.sqrt(delta))/2; x3=(-1*f-Math.sqrt(delta))/2; flag=1; } else { flag=0; } } else { double delta1; delta1=c*c-4*b*d; if(b==0) { flag=-1; x1=-1*d/c; } if(delta1>=0) { x1=(-b+(double)Math.sqrt(delta1))/(2*b); x2=(-b-(double)Math.sqrt(delta1))/(2*b); flag=2; } else flag=-2; }} public void showRoots() { if(flag==-2) { System.out.println("No Roots"); } if(flag==-1) { System.out.println("One Root:"+x1); } if(flag==0) { System.out.println("One Root:"+x1); } if(flag==1) { System.out.println("Three Roots:"); System.out.println("X1="+x1); System.out.println("X2="+x2); System.out.println("X3="+x3); } if(flag==2) { System.out.println("Two Roots:"); System.out.println("X1="+x1); System.out.println("X2="+x2); } } public static void main(String[] args){ double a1=0.0,b1=0.0,c1=0.0,d1=0.0; try{System.out.println("Please Input a"); BufferedReader br= new BufferedReader (new InputStreamReader(System.in)); a1=Double.parseDouble(br.readLine()); System.out.println("Please Input b"); br=new BufferedReader (new InputStreamReader(System.in)); b1=Double.parseDouble(br.readLine()); System.out.println("Please Input c"); br=new BufferedReader (new InputStreamReader(System.in)); c1=Double.parseDouble(br.readLine()); System.out.println("Please Input d"); br=new BufferedReader (new InputStreamReader(System.in)); d1=Double.parseDouble(br.readLine()); }catch(IOException e){} ThirdDegreeEquation TDE= new ThirdDegreeEquation(a1,b1,c1,d1); TDE.calculateRoots(); TDE.showRoots(); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -