How to find the roots of a quadratic equation in C#

1 Answer

0 votes
using System;

class Program
{
    static void quadratic_equation_roots(double a, double b, double c) {
        double discriminant = (b * b) - (4 * a * c);
       
        double root1, root2;
        if (discriminant > 0) {
            root1 = (-b + Math.Sqrt(discriminant)) / (2 * a);
            root2 = (-b - Math.Sqrt(discriminant)) / (2 * a);
            Console.WriteLine("root1 = " + root1 + "\nroot2 = " + root2);
        }
        else if(discriminant == 0) {
            root1 = root2 = -b / (2 * a);
            Console.WriteLine("root1 = root2 = " + root1);
        }
        else if(discriminant < 0) {
            double real = -b / (2 * a);
            double imaginary = Math.Sqrt(-discriminant) / (2 * a);
            Console.WriteLine("root1 = " + real + "+" + imaginary + "i\nroot2 = " + real + "-" + imaginary + "i");
        }
    }
    static void Main() {
        double a = 3, b = 5, c = -9;
  
        quadratic_equation_roots(a, b, c);
        Console.WriteLine();
  
        a = 3; b = 5; c = 7;
        quadratic_equation_roots(a, b, c);
        Console.WriteLine();
  
        a = 2; b = 4; c = 2;
        quadratic_equation_roots(a, b, c);
    }
}




/*
run:
  
root1 = 1.08876043244513
root2 = -2.7554270991118

root1 = -0.833333333333333+1.2801909579781i
root2 = -0.833333333333333-1.2801909579781i

root1 = root2 = -1
  
*/

 



answered Jan 11, 2022 by avibootz

Related questions

1 answer 233 views
1 answer 224 views
1 answer 202 views
1 answer 212 views
1 answer 237 views
1 answer 213 views
1 answer 221 views
...