Design and develop a Java program that continuously computes and
displays value(s) for x, given quadratic equations (i.e. a
second-order polynomials) of the form:
ax2 + bx + c = 0
where the values for the coefficients a, b and c are supplied by the
user, and are assumed to be integers within the range of -100 to 100.
To control the loop use a menu interface. The menu should include two
options: "Calculate quadratic" and "End".
Note that to solve a quadratic equation we must calculate the roots.
This can be done using the quadratic formula:
root 1 = (-b + sqrt(b2-4ac)) / 2a
root2 = (-b - sqrt(b2-4ac)) / 2a
Example:
x2 + 2x - 8 = 0
a= 1, b = 2, c = -8
roots = (-2 +or- sqrt(22-4x1x-8)) / 2x1
= (-2 +or- sqrt(4+32)) / 2
root1 = (-2 + 6)/2 = 4/2 = 2.0
root2 = (-2 - 6)/2 = -8/2 = -4.0
x = 2.0 or -4.0
However, there are certain special consideration to be taken into account:
If a and b are both zero there is no solution (this is referred to as
the degenerate case):
-8 = 0?
a= 0, b = 0, c = -8
(degenerate case)
If a is zero and b is non zero the equation becomes a linear equation.
2x - 8 = 0
a= 0, b = 2, c = -8
(Linear equation)
root = -c/b = 8/2 = 4.0
x = 4.0
If the value for the term b2 - 4ac (the discriminant) is negative
there is no solution (conventionally we cannot find the square root of
a negative number!):
x2 + 2x + 8 = 0
a= 1, b = 2, c = 8
roots = (-2 +or- sqrt(22-4x1x8)) / 2x1
= (-2 +or- sqrt(4-32)) / 2
= (-2 +or- sqrt(-28))
Negative discriminant therefore no solution.
If the discriminant is 0 then there are two identical solutions, i.e.
only one solution (root) need be calculated:
x2 + 4x + 4 = 0
a= 1, b = 4, c = 4
roots = (-4 +or- sqrt(42-4x1x4)) / 2x1
= (-4 +or- sqrt(16-16)) / 2
(Discriminant = 0, there fore only one solution)
root = -4/2 = -2
x = -2.0
Output, where appropriate, should be accurate to at least several decimal places.
Please try to include explanations where appropriate. |