C# Program - Find Roots of a Quadratic Equation


Advertisements

A standard form of a quadratic quation is:

$$ax^2 + bx + c = 0$$

Where:

$$a, b$$ and $$c$$ are real numbers and $$a \ne 0$$.

Roots of the equation are:

$$\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$

For Example:

The roots of equation $$x^2 + 5x + 4 = 0$$ is

$$\frac{-5 \pm \sqrt{5^2 - 4\times1\times4}}{2\times1}$$ = $$\frac{-5 \pm \sqrt{9}}{2}$$ = $$\frac{-5 \pm 3}{2}$$ = $$-4, -1$$

The roots of the equation will be imaginari if $$D = b^2 - 4ac \lt 0$$. For example - the roots of equation $$x^2 + 4x + 5 = 0$$ will be

$$\frac{-4 \pm \sqrt{4^2 - 4\times1\times5}}{2\times1}$$ = $$\frac{-4 \pm \sqrt{-4}}{2}$$ = $$\frac{-4 \pm 2i}{2}$$ = $$-2 \pm i$$


Example: Calculate roots of a Quadratic equation

In the below example, a method called roots is created which takes $$a$$, $$b$$ and $$c$$ as arguemts to calculate the roots of the equation $$ax^2 + bx + c = 0$$.

using System;

namespace MyApplication { 
   class MyProgram {
    static void roots(double a, double b, double c) {
      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("Roots of the equation ax^2 + bx + c = 0 are :");
        Console.WriteLine(x1 + " and " + x2);
        Console.WriteLine("Where a, b, c are " + a + "," + b + " and " + c + " respectively.");     
      } else {
        double x1 = -b/(2*a);
        double x2 = Math.Sqrt(-D)/(2*a);
        Console.WriteLine("Roots of the equation ax^2 + bx + c = 0 are imaginary.");
        Console.WriteLine("Real part of root: " + x1);
        Console.WriteLine("Imaginary part of root: " + x2);
        Console.WriteLine("Where a, b, c are " + a + "," + b + " and " + c + " respectively."); 
      }
    }

    static void Main(String[] args) {
      roots(1,5,4);
      Console.WriteLine();
      roots(1,4,5);
    }
  }
}

Output

Roots of the equation ax^2 + bx + c = 0 are :
-1.0 and -4.0
Where a, b, c are 1 , 5 and 4 respectively.

Roots of the equation ax^2 + bx + c = 0 are imaginary.
Real part of root: -2.0
Imaginary part of root: -1.0
Where a, b, c are 1 , 4 and 5 respectively.



Recommended Pages


Advertisements