Write a program that will determine the roots of quadratic equations ax^2 + bx +c. the program should repeatedly prompt the user for values of a, b, and c. For each set of values, the program should solve the corresponding equation, if it has a solution, or print an appropriate message, if it has no solution.

Your console should look similart to:

Do you want to solve an equation (y/n)? y

Enter a: 1

Enter b: -5

Enter c: 6

Root1: 2.0

Root2: 3.0

Do you want to solve an equation (y/n)? y

Enter a: 1

Enter b: -1

Enter c: 4.25

Root1: real part: 0.5 imaginary part: -2.0

Root2: real part: 0.5 imaginary part: 2.0

Your console should look similart to:

Do you want to solve an equation (y/n)? y

Enter a: 1

Enter b: -5

Enter c: 6

Root1: 2.0

Root2: 3.0

Do you want to solve an equation (y/n)? y

Enter a: 1

Enter b: -1

Enter c: 4.25

Root1: real part: 0.5 imaginary part: -2.0

Root2: real part: 0.5 imaginary part: 2.0

View Answers

March 5, 2010 at 11:49 AM

Hi Friend,

Try the following code:

import java.util.*;

class QuadraticEquation

{

public static void main(String[]args){

Scanner input=new Scanner(System.in);

System.out.print("Do you want to solve an equation (y/n): ");

String st=input.next();

if(st.equals("y")){

System.out.print("Enter the value of a: ");

double a=input.nextDouble();

System.out.print("Enter the value of b: ");

double b=input.nextDouble();

System.out.print("Enter the value of c: ");

double c=input.nextDouble();

double eq=b*b-4*a*c;

double r1= -b+Math.sqrt(eq);

double r2= -b-Math.sqrt(eq);

double Root1=r1/2*a;

double Root2=r2/2*a;

System.out.println("Root 1 ="+Root1);

System.out.println("Root 2 ="+Root2);

}

else{

System.exit(0);

}

}

}

Thanks

Try the following code:

import java.util.*;

class QuadraticEquation

{

public static void main(String[]args){

Scanner input=new Scanner(System.in);

System.out.print("Do you want to solve an equation (y/n): ");

String st=input.next();

if(st.equals("y")){

System.out.print("Enter the value of a: ");

double a=input.nextDouble();

System.out.print("Enter the value of b: ");

double b=input.nextDouble();

System.out.print("Enter the value of c: ");

double c=input.nextDouble();

double eq=b*b-4*a*c;

double r1= -b+Math.sqrt(eq);

double r2= -b-Math.sqrt(eq);

double Root1=r1/2*a;

double Root2=r2/2*a;

System.out.println("Root 1 ="+Root1);

System.out.println("Root 2 ="+Root2);

}

else{

System.exit(0);

}

}

}

Thanks

Related Tutorials/Questions & Answers: