Java基础语法实战系统总结2(陆续上传中...)

利用Java API,查找到Math类,求一元二次方程?提示用Math类中的开方sqrt,求幂pow等等。SolveQuadratic.java
/** 求解二次方程 a*x*x+b*x+c=0
  * b*b-4*a*c=0, 有两个相等实根
  * b*b-4*a*c>0, 有两个相异实根 
  * b*b-4*a*c<0, 有两个共轭复根 
  */
import javax.swing.*;
public class SolveQuadratic{
  public static void main(String[] args){
    if(args.length!=3){
      System.out.println("Usage: java SolveQuadratic aCoef  bCoef cCoef");
      System.out.println("Example: java SolveQuadratic 1 2 1");
      System.exit(-1);
    }
    double a;
    double b;
    double c;
    a=Double.parseDouble(args[0]);     
    if(Math.abs(a)<Math.pow(10,-6)){ //认为a等于0
      System.out.println("a=0, not a Quadratic");
      System.exit(-1);
    }  
    b=Double.parseDouble(args[1]);
    c=Double.parseDouble(args[2]);
    System.out.println("Quadratic is "+a+"*x*x+"+b+"*x+"+c+"=0");
   
    double disc=b*b-4*a*c;
   
    if(Math.abs(disc)<Math.pow(10,-6)){ //认为disc等于0
      System.out.println("The Quadratic has two equal roots:"+(-b/(2*a)));
    }else if(disc>Math.pow(10,-6)){ //disc大于0
      double root1=(-b+Math.sqrt(disc))/(2*a);
      double root2=(-b-Math.sqrt(disc))/(2*a);
      System.out.println("The Quadratic has two distinct roots:"+root1+" "+root2);
    }else{//disc小于0
      double realPart=-b/(2*a);
      double imagPart=Math.sqrt(-disc)/(2*a);
      System.out.println("The Quadratic has complex roots:");
      System.out.println(realPart+"+"+imagPart+"i");
      System.out.println(realPart+"-"+imagPart+"i");
    } 
  } 
}

你可能感兴趣的:(java,C++,c,C#)