-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathProblem$25.java
60 lines (47 loc) · 1.73 KB
/
Problem$25.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package chapter_seven;
import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;
/**
* 7.25 (Algebra: solve quadratic equations) Write a method for solving a quadratic
* equation using the following header:
* public static int solveQuadratic(double[] eqn, double[] roots)
* The coefficients of a quadratic equation ax2 + bx + c = 0 are passed to the array
* eqn and the real roots are stored in roots. The method returns the number of real
* roots. See Programming Exercise 3.1 on how to solve a quadratic equation.
* Write a program that prompts the user to enter values for a, b, and c and displays
* the number of real roots and all real roots.
*
* @author Sharaf Qeshta
* */
public class Problem$25
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in).useLocale(Locale.US);
System.out.print("Enter a, b, c: ");
double[] eqn = new double[3], roots = new double[2];
for (int i = 0; i < 3; i++)
eqn[i] = scanner.nextDouble();
System.out.println("there are " + solveQuadratic(eqn, roots) + " real roots");
System.out.println(Arrays.toString(roots));
}
public static int solveQuadratic(double[] eqn,
double[] roots)
{
double discriminant = (eqn[1] * eqn[1]) - (4 * eqn[0] * eqn[2]);
if (discriminant > 0)
{
roots[0] = (-eqn[1] + Math.sqrt(discriminant)) / (2 * eqn[0]);
roots[1] = (-eqn[1] - Math.sqrt(discriminant)) / (2 * eqn[0]);
return 2;
}
else if (discriminant < 0 )
return -1;
else
{
roots[0] = (-eqn[1]) / (2 * eqn[0]);
return 1;
}
}
}