Java program Roots of Quadratic Equation
The solution or root of quadratic equation is found by the Java programming code. The equation coefficient a,b,c are inputs and returns x1 and x2 are roots of the equation.
Quadratic Equation - Java programming code
The Java program is to find root of quadratic equation. The coefficients of the quadratic equation are input of the program. They are read from user at run time and returns solutions x1 and x2 as root of the quadratic equation.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class QuadtraticEqu {
public static void main(String[] args) throws IOException {
InputStreamReader dis =new InputStreamReader ( System.in );
BufferedReader br =new BufferedReader(dis);
System.out.println("Root of Quadratic Equation");
System.out.println("Enter value for a");
String arg1 =br.readLine();
int a = Integer.parseInt(arg1);
System.out.println("Enter value for b");
String arg2 =br.readLine();
int b = Integer.parseInt(arg2);
System.out.println("Enter value for c");
String arg3 =br.readLine();
int c = Integer.parseInt(arg3);
double tmp =b*b - 4*a*c;
double tmp2 = 2.0*a;
if ( tmp>0 ) {
double x1 = (-b + Math.sqrt(tmp) ) / tmp2;
double x2 = (-b - Math.sqrt(tmp) ) / tmp2;
System.out.println(" Root of the Equation is x=" + x1 +"," +x2 );
}
else {
String xtmp = -b + "+sqrt("+ tmp +")i/" + 2*a;
String xtmp2 = -b + "-sqrt("+ tmp +")i/" + 2*a;
System.out.println("Root of the Equation is x="+xtmp+"\t"+xtmp2);
}
}
}
Quadratic Equation - Java program output
Root of Quadratic Equation Enter value for a 4 Enter value for b 6 Enter value for c 2 Root of the Equation is x=-0.5,-1.0
Comments
Post a Comment