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 discriminate b2-4ac is negative, display a message stating that there are no real solutions.



Program Code in JAVA:
import java.io.*;
import java.math.*;
class Quad
{
public static void main(String[] args) throws Exception
{
int a,b,c,d;
float r1,r2;
System.out.println("Enter a , b & c values");
DataInputStream dis=new DataInputStream(System.in);
a=Integer.parseInt(dis.readLine());
b=Integer.parseInt(dis.readLine());
c=Integer.parseInt(dis.readLine());
d=(b*b)-(4*a*c);
if (d==0)
{
r1=r2=(float)(-b/(2*a));
System.out.println("The roots are equal\nr1="+r1+" and r2="+r2);
}
else if(d>0)
{
r1=(float)(-b+Math.sqrt(d))/(2*a);
r2=(float)(-b-Math.sqrt(d))/(2*a);
System.out.println("The roots are real & distinct\n r1="+r1+" and r2="+r2);
}
else if(d<0)
{
r1=(float)(-b/(2*a));
r2=(float)(Math.sqrt(-d)/(2*a));
System.out.println("The roots are complex &
imaginary\nr1="+r1+"+i"+r2+"\nr2="+r1+"-i"+r2);
}
}
}


Program Output:
c:\java>javac Quad.java
c:\java>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
Mukesh Rajput

Mukesh Rajput

I am a Computer Engineer, a small amount of the programming tips as it’s my hobby, I love to travel and meet people so little about travel, a fashion lover and love to eat food, I am investing a good time to keep the body fit so little about fitness also..

Post A Comment:

0 comments: