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");
    			}
    	}
    }



  • 相关阅读:
    struts2_文件上传和下载
    struts2_方法拦截器
    struts2_Action之间的重定向传参
    struts2_全局的拦截器,拦截用户非法登陆
    Hibernate入门心得
    struts2_异常页面处理
    设计师小法器:字体大管家
    IE6,IE7下设置body{overflow:hidden;}失效Bug【转】
    子层的margintop属性应用到父层上的解决方法
    jQuery CSS选择器nthchild
  • 原文地址:https://www.cnblogs.com/xinyuyuanm/p/3030714.html
Copyright © 2011-2022 走看看