The two roots of a quadratic equation ax2 + bx + c = 0 can be obtained using the following formula:
b2 - 4ac is called the discriminant of the quadratic equation. If it is positive, the equation has two real roots. If it is zero, the equation has one root. If it is negative, the equation has no real roots.
Write a program that prompts the user to enter values for a, b, and c and displays the result based on the discriminant. If the discriminant is positive, display two roots. If the discriminant is 0 , display one root. Otherwise, display “The equation has no real roots”.
Solution:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double a, b, c;
double discriminant, r1, r2;
System.out.print("Enter a, b, c:");
a = s.nextDouble();
b = s.nextDouble();
c = s.nextDouble();
discriminant = Math.pow(b, 2) - 4 * a * c;
if(discriminant > 0) {
r1 = (-b + Math.pow(discriminant, 0.5)) / (2 * a);
r2 = (-b - Math.pow(discriminant, 0.5)) / (2 * a);
System.out.print("The equation has two roots " + r1 + " and " + r2 + ".");
} else if(discriminant == 0) {
r1 = (-b) / (2 * a);
System.out.print("The equation has one root " + r1 + ".");
} else {
System.out.print("The equation has no real roots.");
}
}
Doesn't work for me..
ReplyDeleteI'm studying Java by myself and am struggling quite a bit.
The error says "QuadraticEquation cannot be resolved to a type"
Very nice post.Thanks for sharing your knowledge to us.This is very helpfull programming post.
ReplyDeleteAdvantages Of DBMS Over File Management System