Untitled

 avatar
unknown
plain_text
a year ago
1.7 kB
19
Indexable
public class Main {
    public static void main(String[] args) {

        double result;

        System.out.print("Input coefficient 'a': ");
        double a = userNum();

        System.out.print("Input coefficient 'b': ");
        double b = userNum();

        System.out.print("Input coefficient 'c': ");
        double c = userNum();

        result = b * b - 4.0 * a * c;

        calcPrint(a, b, result);

    }

    public static double userNum ()
    {
        Scanner input = new Scanner(System.in);

        return input.nextDouble();

    }

    public static double round(double value, int places)
    {
        if (places < 0) throw new IllegalArgumentException();

        long factor = (long) Math.pow(10, places);
        value = value * factor;
        long tmp = Math.round(value);
        return (double) tmp / factor;
    }

    public static void calcPrint(double a, double b, double result)
    {

        int decimalPlaces = 2;

        if (result > 0)
        {
            double r1 = (-b + Math.pow(result, 0.5)) / (2.0 * a);
            double r2 = (-b - Math.pow(result, 0.5)) / (2.0 * a);
            System.out.println("Root 1: " + r1 + " \u2248 " + round(r1, decimalPlaces));
            System.out.println("Root 2: " + r2 + " \u2248 " + round(r2, decimalPlaces));
        }
        else if (result == 0.0)
        {
            double r1 = -b / (2.0 * a);
            System.out.println("Root 1: " + r1 + " \u2248 " + round(r1, decimalPlaces));
        }
        else
        {
            System.out.println("The equation has no real roots.");
        }
    }



}
Editor is loading...
Leave a Comment