Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

A simple program to solve quadratic equations with

4.00/5 (1 vote)
9 Nov 2010CPOL 6.8K  
// Real solutions of the quadratic equation A x^2 + B x + C = 0// Returns two roots (possibly identical) in increasing order, or nonebool Quadratic(double A, double B, double C, double R[2]){ if (A == 0) { // Linear, impossible or degenerate, cannot find two roots ...
C#
// Real solutions of the quadratic equation A x^2 + B x + C = 0
// Returns two roots (possibly identical) in increasing order, or none
bool Quadratic(double A, double B, double C, double R[2])
{
    if (A == 0)
    {
        // Linear, impossible or degenerate, cannot find two roots
        return false;
    }

    // Truly quadratic, reduce the coefficients and discuss
    A= 1 / A;
    B*= 0.5 * A;
    C*= A;
    double D= B * B - C;
    if (D < 0)
    {
        // No real root
        return false;
    }

    // Compute and sort the root(s), avoiding cancellation and division by zero
    double Q= - B + (B > 0 ? - sqrt(D) : + sqrt(D));
    R[0]= Q > 0 ? C / Q : Q;
    R[1]= Q < 0 ? C / Q : Q;

    return true;
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)