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.

//Program to find roots of a quadratic equations
import java.util.*;
class Roots
{
            public static void main(String args[])
            {
                        int a,b,c,d,f=0;
                        Scanner scr=new Scanner(System.in);
                        System.out.println(“nEnter the values of a ,b ,c : “);
                        a=scr.nextInt();
                        b=scr.nextInt();
                        c=scr.nextInt();
                        d=(b*b)-(4*a*c);
                        if(d==0)
                        {
                                    System.out.println(“Roots are real and Equal”);
                                    f=1;
                        }
                        else if(d>0)
                        {
                                    System.out.println(“Roots are real and UnEqual”);
                                    f=1;
                        }
                        else
                        System.out.println(“Roots are imaginary”);
                        if(f==1)
                        {
                                    float r1=(float)(-b+Math.sqrt(d))/(2*a);
                                    float r2=(float)(-b-Math.sqrt(d))/(2*a);
                                    System.out.println(“Roots are :   “+r1+” ,”+r2);
                        }
            }
}
                       
Output:
Enter the values of a ,b ,c :
1
2
-3
Roots are real and UnEqual

Roots are :   1.0 ,-3.0

3 Comments

  1. The Outpud should be like this right ?
    Output: D:Lab>javac Quad.java
    D:Lab>java Quad
    Enter a, b & c values 3 2 1
    The roots are complex & imaginary
    r1=0.0+i0.47140452 r2=0.0-i0.47140452

    can anyone help us

Leave a Reply

Your email address will not be published. Required fields are marked *

Enable Notifications OK No thanks