66 909
Assignments Done
99,1%
Successfully Done
In October 2018

Answer to Question #48934 in Java | JSP | JSF for felly

Question #48934

Write a program to compute the roots (x1, x2) of a quadratic equation.
X=( -b ± √b²-4ac)/2a
Expert's answer
import java.util.Scanner;
public class Roots {

static double a,b,c;
static double delta;
static double x1,x2,x3;
static double Q,R,Teta;

public static void main(String[] args) {

System.out.println("Enter the coefficients for the quadratic equation");
Scanner s = new Scanner(System.in);
System.out.print("a->");
a = s.nextDouble();
System.out.print("b->");
b = s.nextDouble();
System.out.print("c->");
c = s.nextDouble();

delta = Math.pow(b,2)-4*a*c;
if (delta<0)
{
System.out.println("delta =" + delta);
System.out.println("The quadratic equation has no real roots ");
}
else
{
x1=(-b - Math.sqrt(delta))/(2*a);
x2=(-b + Math.sqrt(delta))/(2*a);
System.out.println("delta =" + delta);
System.out.println("The quadratic equation has 2 distinct real roots");
System.out.println("x1 =" + x1);
System.out.println("x2 =" + x2);

}
// TODO Auto-generated method stub

System.out.println("Enter the coefficients for the cubic equation");
Scanner cb = new Scanner(System.in);
System.out.print("a->");
a = cb.nextDouble();
System.out.print("b->");
b = cb.nextDouble();
System.out.print("c->");
c = cb.nextDouble();
delta = 4*Math.pow(a,3)*c-Math.pow(a,2)*Math.pow(b,2)+4*Math.pow(b,3)-18*a*b*c+27*Math.pow(c,2);
if (delta<0)
{
System.out.println("delta =" + delta);
System.out.println(" Then cubic equation has three distinct roots. ");
Q=(1.0/9)*(Math.pow(a, 2)-3*b);
R=(1.0/54)*(2*Math.pow(a, 3)-9*a*b+27*c);
Teta=Math.acos( R/ Math.sqrt(Math.pow(Q,3)) );

x1=-2*Math.sqrt(Q)*Math.cos(Teta/3)- (1.0/3)*a;
x2=-2*Math.sqrt(Q)*Math.cos( (Teta+2*Math.PI)/3)- (1.0/3)*a;
x3=-2*Math.sqrt(Q)*Math.cos( (Teta-2*Math.PI)/3)- (1.0/3)*a;
System.out.println("x1 =" + x1);
System.out.println("x2 =" + x2);
System.out.println("x3 =" + x3);
}
else
{
System.out.println("delta =" + delta);
System.out.println("The cubic equation has one real root and 2 complex conjugate roots");

}


}}


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions