Solving the Quadratic Formula in C#

Here’s a quick bit of code that solves the quadratic formula [math]x=\frac{-b\pm\sqrt{b^2-4ac}}{2a}[/math] in C#. It doesn’t give exact answers, thats the only down-fall. It is limited by how many numbers after the decimal point can be displayed on the console screen.

Anyway, here it is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

 

namespace QuadraticSolver
{
class Program
{
static void Main(string[] args)
{
double a, b, c;

Console.WriteLine(“In the form of f(x) = a(x)^2+b(x)+c, fill in the variables for a, b, and c:”);

Console.Write(“a = ?: “);
a = double.Parse(Console.ReadLine().Trim());

Console.Write(“b = ?: “);
b = double.Parse(Console.ReadLine().Trim());

Console.Write(“c = ?: “);
c = double.Parse(Console.ReadLine().Trim());

Console.WriteLine(“————————–”);

if (a > 0)
Console.WriteLine(“Parabola has a minimum value and opens upward.”);
else
Console.WriteLine(“Parabola has a maximum value and opens downward.”);

double xInt1, xInt2;

/*
* x = ( -(b) +/- sqrt( (-b)^2 – 4(a)(c) ) ) / 2(a) )
**/

double part1 = Math.Sqrt(Math.Pow(-b, 2) – 4 * a * c);

xInt1 = (-(b) + part1) / (2 * a);
xInt2 = (-(b) – part1) / (2 * a);

Console.WriteLine(“X-Intercepts are: ({0},0) ; ({1},0)”, xInt1, xInt2);
Console.WriteLine(“Y-Intercept is: (0,{0})”, c);

double vertX, vertY;
vertX = (-b / (2 * a));
vertY = (((4 * a * c) – Math.Pow(b, 2)) / (4 * a));

Console.WriteLine(“Vertex Coords: ({0},{1})”, vertX, vertY);

Console.WriteLine(“Press <ENTER> to close…”);
Console.ReadLine();
}
}
}

 

 

Leave a reply