**Create a program in Java, which receives the coefficients of an equation of the second degree and return their roots.**

**A quadratic equation is an equation where:**

**ax ² + bx + c = 0, with 'a' different from 0**

### Step 1:

The first part of the program receives three equation coefficients, which are 'a', 'b' and 'c' and will be represented by the type float.### Step 2:

An equation of the second degree is valid only if 'a' is different from 0. Then, if 'a' equals 0, the program should end.

That is, our program will happen within the 'if' that checks that 'a' is different from 0.

### Step 3:

Determining the value of delta: delta = b ² - 4ac

Determining the square root of delta: sqrtdelta = (float) Math.sqrt (delta);

In Java, we calculate the square root of the number x with the method: Math.sqrt (x);

This method returns a type 'double'. How we use float in our coefficients, we use the cast '(float)' to turn the double to float.

### Step 4:

If delta is greater than or equal to zero, the roots are given by:

root1 = (-b + sqrtdelta) / second

root2 = (-b - sqrtdelta) / second

### Step 5:

If delta is less than zero, its roots will be complex and the roots are of the form:

root1 = (-b + i.sqrt (delta)) / 2a

root2 = (-b - i.sqrt (-delta)) / 2a

The output formatted as follows to become more legible, that is the same as the previous equations:

root1 = (-b) / 2a + i.sqrt (delta) / 2a

root2 = (-b) / 2a - i.sqrt (delta) / 2a

Java code:

```
import java.util.Scanner;
public class Bhaskara {
public static void main(String[] args) {
float a, b, c, //coefficientes
delta, //delta
sqrtdelta, //squareroot of delta
root1,root2; //roots
Scanner input = new Scanner(System.in);
// Step 1: Receiving the coefficients
System.out.println("Equation of second degree: ax² + bx + cx = 0");
System.out.print("Enter with the value of a: ");
a = input.nextFloat();
System.out.print("Enter with the value of b: ");
b = input.nextFloat();
System.out.print("Enter with the value of c: ");
c = input.nextFloat();
// Step 2: checking if the equation is valid
if(a != 0){
// Step 3: getting the value of delta and calculating its square root
delta = (b*b) - (4*a*c);
sqrtdelta = (float)Math.sqrt(delta);
// Step 4: if the root delta is greater than 0, the roots are real
if(delta >=0){
root1 = (-b + sqrtdelta)/(2*a);
root2 = (-b - sqrtdelta)/(2*a);
System.out.printf("Roots: %.2f e %.2f", root1, root2);
}
// Step 5: If delta is less than 0, the roots will be complex
else{
delta = -delta;
sqrtdelta = (float)Math.sqrt(delta);
System.out.printf("Root 1: %.2f + i.%.2f\n", (-b)/(2*a), (sqrtdelta)/(2*a));
System.out.printf("Root 2: %.2f - i.%.2f\n", (-b)/(2*a), (sqrtdelta)/(2*a));
}
}
else{
System.out.println("Coefficient 'a' invalid. There is not a second degree equation");
}
}
}
```

## No comments:

Post a Comment