-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRootsOfQuaeq.java
57 lines (42 loc) · 1.26 KB
/
RootsOfQuaeq.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
// Java program to find the roots of
// quadratic equation
public class RootsOfQuaeq {
public static void main(String[] args)
{
// value of the constants a, b, c
double a = 7.2, b = 5, c = 9;
// declared the two roots
double firstroot, secondroot;
// determinant (b^2 - 4ac)
double det = b * b - 4 * a * c;
// check if determinant is greater than 0
if (det > 0) {
// two real and distinct roots
firstroot = (-b + Math.sqrt(det)) / (2 * a);
secondroot = (-b - Math.sqrt(det)) / (2 * a);
System.out.format(
"First Root = %.2f and Second Root = %.2f",
firstroot, secondroot);
}
// check if determinant is equal to 0
else if (det == 0) {
// two real and equal roots
// determinant is equal to 0
// so -b + 0 == -b
firstroot = secondroot = -b / (2 * a);
System.out.format(
"First Root = Second Root = %.2f;",
firstroot);
}
// if determinant is less than zero
else {
// roots are complex number and distinct
double real = -b / (2 * a);
double imaginary = Math.sqrt(-det) / (2 * a);
System.out.printf("First Root = %.2f+%.2fi",
real, imaginary);
System.out.printf("\nSecond Root = %.2f-%.2fi",
real, imaginary);
}
}
}