QuestionAsk Questions?

The roots of the quadratic equation ax2+bx+c=0, aÃ¯â??Â¹0 are given by the following formula: x=(-bÃ?Â±Ã¢Ë?Å¡(b^2-4ac))/2a

In this formula. The term b2-4ac is called the discriminant . If b2-4ac=0, Then the equation has a single(repeated) root. If b2-4ac<0, the equation has two complex roots. Write a program that prompts the user to input the value of a(the coefficient of x2), b(the coefficient of x), and c (the constant term, and output the types of roots of the equation. Furthermore, if b2- 4ac Ã¢â?°Â¥ 0, the program should output the roots of the quadratic equation. (Hint: Use the method pow or sqrt from the class Math to calculate the square root.

View Answers

September 19, 2012 at 4:56 PM

Here is a java example that finds the roots of the quadratic equation.

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

Related Tutorials/Questions & Answers: