Solving A QuadraticEquation by Java

Purpose:
	This program solves for the roots
	of a quadratic equation of the form
	a*x*x+b*x+c=0. It calculates the
	answers regardless of the type of
	roots 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 discriminant
		discriminant=b*b-4*a*c;

		//Solve for the roots,depending on the discriminant.
		if(discriminant>0)
		{
			//Two real roots
			x1=(-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);
		}
		else
			if(discriminant==0)
			{
				//One repeated root
				x1=(-b)/(2*a);
				System.out.println("This equation has repeated real roots:");
				System.out.println("X1 = X2 = "+x1);
			}
			else
			{
				//Two complex root
				real_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");
			}
	}
}



原文地址:https://www.cnblogs.com/xinyuyuanm/p/3030714.html