zoukankan      html  css  js  c++  java
  • 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");
    			}
    	}
    }



  • 相关阅读:
    关于SQL
    win10商店或者账户连不上网
    pom.xml红叉
    3D球状标签云(兼容IE8)
    网页宽高自适应大小
    html5定位并在百度地图上显示
    【转】Javascript 中的false,零值,null,undefined和空字符串对象
    jQuery checkBox 全选的例子
    jQuery 表单验证 jquery.validator.js
    jQuery 手风琴侧边菜单
  • 原文地址:https://www.cnblogs.com/xinyuyuanm/p/3030714.html
Copyright © 2011-2022 走看看