Solving A QuadraticEquation by Java

来源:互联网 发布:最好的漫画软件 编辑:程序博客网 时间:2024/05/01 04:39
Purpose:This program solves for the rootsof a quadratic equation of the forma*x*x+b*x+c=0. It calculates theanswers regardless of the type ofroots that the equation possesses.import java.io.*;public class QuadraticEquation{//Define the main method.public static void main(String[] args) throws IOException{//Declare variables,and define each variable.double a;double b;double c;double discriminant;double imag_part;double real_part;double x1;double x2;//Create a buffered reader.BufferedReader inl=new BufferedReader(new InputStreamReader(System.in));//Prompt the user for the coefficients of the equation.System.out.println("This program solves for the roots of quadratic equation.");System.out.println("Please input the coefficients of quadratic equation:");System.out.print("Enter the coefficients A: ");a=Double.parseDouble(inl.readLine());System.out.print("Enter the coefficients B: ");b=Double.parseDouble(inl.readLine());System.out.print("Enter the coefficients C: ");c=Double.parseDouble(inl.readLine());System.out.println("The quadratic equation you inputed is:");System.out.println(a+"*x*x + "+b+"*x + "+c+" = 0");//Caluate discriminantdiscriminant=b*b-4*a*c;//Solve for the roots,depending on the discriminant.if(discriminant>0){//Two real rootsx1=(-b+Math.sqrt(discriminant))/(2*a);x2=(-b-Math.sqrt(discriminant))/(2*a);System.out.println("This equation has two real roots:");System.out.println("X1 = "+x1+" , X2 = "+x2);}elseif(discriminant==0){//One repeated rootx1=(-b)/(2*a);System.out.println("This equation has repeated real roots:");System.out.println("X1 = X2 = "+x1);}else{//Two complex rootreal_part=(-b)/(2*a);imag_part=Math.sqrt(Math.abs(discriminant))/(2*a);System.out.println("This equation has two Complex roots:");System.out.println("X1 = "+real_part+"+"+imag_part+"i");System.out.println("X2 = "+real_part+"-"+imag_part+"i");}}}