15. QuadraticEquations

This program solves randomly generated quadratic equations -> ax² + bx + c = 0. Where a, b, and are integers between 0 and 10. This range can be easily changed in the program to solve other equations.

Description: This program solves randomly generated quadratic equations -> ax² + bx + c = 0. Where a, b, and are integers between 0 and 10. This range can be easily changed in the program to solve other equations.

Code

package asu.quadraticequations;

public class QuadraticEquations {
    
    public static void main(String[] args) {
        //quadratic equation
        // x = (-b + 0 sqrt(b squared - 4 a c )/2a
        //note: can't take sqrt of a negative number
        
            int a = randomInteger(0, 10);
            int b = randomInteger(0, 10);
            int c = randomInteger(0, 10);
            
            System.out.println("a = " + a);
            System.out.println("b = " + b);
            System.out.println("c = " + c);
            
            System.out.println("The quadratic equations:");
            
            System.out.println(a + "x^2 + " + b + "x + " + c + " = 0 ");
            
            System.out.println("Has solutions:");
            
            if (a == 0) {
                System.out.println("x = " + -c / b);
                System.exit(1);
            }
            double discriminant = Math.pow(b, 2) - 4 * a * c;
            if (discriminant >= 0) {
                double x1 = (-b + Math.sqrt(discriminant))/(2 * a);
                double x2 = (-b - Math.sqrt(discriminant))/(2 * a);
                System.out.println("Real solutions:");
                System.out.println("x1 = " + x1);
                System.out.println("x2 = " + x2);
            } else {
                double c1_real = -b / (2 * a);
                double c2_real = -b / (2 * a);
                double c1_imaginary = Math.sqrt(-discriminant)/(2 * a);
                double c2_imaginary = -Math.sqrt(-discriminant)/(2 * a);
                System.out.println("Complex solutions:");
                System.out.println("c1_real = " + c1_real);
                System.out.println("c1_imaginary = " + c1_imaginary);
                System.out.println("c2_real = " + c2_real);
                System.out.println("c2_imaginary = " + c2_imaginary);
            }
    }
    
    private static int randomInteger(int a, int b) {
        return (int) ((b - a) * Math.random() + a);
    }
}

Output

a = 5
b = 9
c = 3
The quadratic equations:
5x^2 + 9x + 3 = 0 
Has solutions:
Real solutions:
x1 = -0.44174243050441603
x2 = -1.3582575694955838

Last updated