Home Tutorial Java Core Java find the roots of quadratic equation

 
 

Share on Google+Share on Google+
Java find the roots of quadratic equation
Posted on: December 15, 2012 at 12:00 AM
Advertisement
In this tutorial, you will learn how to find the roots of quadratic equation.

Java find the roots of quadratic equation

In this tutorial, you will learn how to find the roots of quadratic equation. Quadratic Equations are always in the form ax2 + bx + c = 0. Every Quadratic equation has two roots. And this program is implemented to find the roots of the quadratic equation. The given example 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 roots of the equation.

Example:

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

Output:

Do you want to solve an equation (y/n): y
Enter the value of a: 3
Enter the value of b: 4
Enter the value of c: 1
Root 1 =-3.0
Root 2 =-9.0
Advertisement

Related Tags for Java find the roots of quadratic equation:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 15, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com