Java class solves the root of a quadratic equation

Source: Internet
Author: User

Strong http://blog.csdn.net/microtong
Oak CMS Content Management System http://www.oakcms.cn http://www.oakcms.net

 

The quadratic equation ax2 + bx + c = 0. Input three coefficients A, B, and C to solve the equation. The results are as follows: two real number roots, one real number root, and two complex numbers.

 

/**
* Equation. Java
*/
Package cn.edu. UIBE. Oop;
/**
* Calculate the root of a quadratic equation
* @ Author Tongqiang
*
*/
Public class equation {
Double A, B, C; // coefficient of the equation
Double x1, x2; // two
Double R; // real part
Double V; // virtual part
Int type; // 0 indicates a root, 1 indicates two solid roots, and 2 indicates the root of two complex numbers.
Public equation (double A, double B, double C ){
This. A =;
This. B = B;
This. C = C;
}
Private Double Delta (){
Return B * B-4 * a * C;
}
Public void calculate (){
Double D = delta ();
If (math. Abs (d) <1e-5 ){
Type = 0;
X1 =-B/(2 * );
X2 = x1;
} Else if (D> 0 ){
Type = 1;
X1 = (-B + math. SQRT (D)/(2 * );
X2 = (-b-Math.sqrt (D)/(2 * );
} Else {
Type = 2;
R =-B/(2 * );
V = math. SQRT (-d)/(2 * );
}
}
Public void showresult (){
Switch (type ){
Case 0:
System. Out. println ("the equation has only one solid root, X1 = x2 =" + X1 );
Break;
Case 1:
System. Out. println ("the equation has two solid roots: X1 =" + X1 + "/tx2 =" + x2 );
Break;
Case 2:
System. out. println ("the equation has two plural roots:" + R + "+" + V + "I, /t "+ R +"-"+ V +" I ");
Break;
}
}

Public static void main (string [] ARGs ){
Equation EQ1 = new equation (1, 2 );
Eq1.calculate ();
Eq1.showresult ();
Equation eq2 = new equation (1,-2, 1 );
Eq2.calculate ();
Eq2.showresult ();
Equation eq3 = new equation (1, 6, 5 );
Eq3.calculate ();
Eq3.showresult ();
}

}

Strong http://blog.csdn.net/microtong
Oak CMS Content Management System http://www.oakcms.cn http://www.oakcms.net

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.