CSharp - Write program to Solve the Quadratic Equation

Requirements

You will write a program to solve a quadratic equation, ax*x + bx + c = 0.

An example of a quadratic equation is x*x ? x - 2 = 0 with a being 1, b being -1, and c being -2.

The equation to be solved will be entered in the form of the coefficients a, b, and c.

The program calculates and displays its solution.

For the sake of simplicity, you will not consider the case of a equal to zero.

Hint

  • For D > 0, the equation has two solutions given by the following:
  • For D = 0, the same formula applies with the two solutions coinciding.
  • For D < 0, the equation does not have a solution in real numbers.
double d = b * b - 4 * a * c;

      -b +   d 
x1 =---------------
         2a 
                                                  
      -b -   d 
x2 =---------------
         2a 

Demo

using System;


class Program/*from   w w  w.ja v a2 s . c  o m*/
{
    static void Main(string[] args)
    {
        // Inputs 
        Console.Write("Enter a: ");
        string input = Console.ReadLine();
        double a = Convert.ToDouble(input);

        Console.Write("Enter b: ");
        string inputB = Console.ReadLine();
        double b = Convert.ToDouble(inputB);

        Console.Write("Enter c: ");
        string inputC = Console.ReadLine();
        double c = Convert.ToDouble(inputC);

        // Solving + output 
        double d = b * b - 4 * a * c;
        if (d > 0)
        {
            double x1 = (-b - Math.Sqrt(d)) / (2 * a);
            double x2 = (-b + Math.Sqrt(d)) / (2 * a);
            Console.WriteLine("The equation has two solutions:");
            Console.WriteLine(x1);
            Console.WriteLine(x2);
        }
        if (d == 0)
        {
            double x = -b / (2 * a);
            Console.WriteLine("The equation has a single solution: " + x);
        }
        if (d < 0)
        {
            Console.WriteLine("The equation does not have a solution");
        }
    }
}

Result