Written by Sai Sameera Thota on May 29, 2013 in Java > Programming

Java Program to find all the Real Solutions of Quadratic Equation

GET ALERTS:

Get our Latest updates delivered to your mailbox!

Problem: Write a Java program that prints all real solutions to the quadratic equation ax2 + bx + c = 0. Read in
a, b, c and use the quadratic formula. If the discriminant b2 -4ac is negative, display a message stating
that there are no real solutions.

Solution:The program takes the coefficients of the quadratic equation as input and prints
two real solutions of the equation if the discriminant is greater than zero, one real solution if
the discriminant is equal to zero and if the discriminant is less than zero, the equation does not
give any real solutions

import java.util.*; 
import java.io.*;

class quadratic 
{

 public static void main(String[] args)
 {
	try 
	{
		System.out.println("\n----- QuadraticEquation : ax^2+bx+c=0 -----\n");
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		System.out.print("\nEnter Value for a: ");
		int a = Integer.parseInt(br.readLine());

		System.out.print("\nEnter Value for b: ");
		int b = Integer.parseInt(br.readLine());

		System.out.print("\nEnter Value for c: ");
		int c = Integer.parseInt(br.readLine());

		long discriminant = (b * b) - (4 * a * c);

		if (discriminant < 0) 
		{
			System.out.println("\nNo Real Solutions");
		} 
		else if (discriminant == 0)
		{
			double root = (-b) / (2 * a);
			System.out.println("\nReal Solution: " + root);
		} 
		else
		{
			double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
			double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);

			System.out.println("\nReal Solution1: " + root1);
			System.out.println("\nReal Solution2: " + root2);
		}

	}
	catch (Exception e)
	{
		e.printStackTrace();
	}
  }
}

Output:quadratic

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: