Tuesday, 28 July 2015

Solve Quadratic Equation


/*
 * C Program to solve quadratic equation.
 * Quadratic Equation ->  ax^2 + bx + c = 0
 * Given - values of a, b and c.
 * We need to find out values of roots of x.
 * Formula to calculate roots of x is as follows : 
 *        
 *     
 *          
 */

// Include section
#include<stdio.h>
#include<string.h>
#include<math.h>

// Declarations
// Structure to represent roots of a quadratic equation.
typedef struct
{
    float root1;                // quadratic root 1
    float root2;                // quadratic root 2
    int   isImaginary:1;        // to represent imaginary value.
    int   errorCode;            // In case there is any problem - error code.
    char  errorDescription[50]; // Short error description.
} quadRoots;

/*
 * solveQuadraticEq
 * Description : Function to solve quadratic equation.
 * Parameters  : a, b, c values of a quadratic equation.
 * Return      : Returns quadRoots structure containing roots of a quadratic equation.
 */
quadRoots solveQuadraticEq(int a, int b, int c);

// Definitions
int main()
{
int a=0,b=0,c=0;
printf("Enter values of a,b,c in following quadratic equation :\n");
printf("ax^2 + bx + c = 0\n");
scanf("%d %d %d",&a,&b,&c);
    
    // Solve Quadratic Equation
    quadRoots result = solveQuadraticEq(a,b,c);
    if (result.errorCode != 0// Error occurred
    {
        printf("Error : %s\n",result.errorDescription);
    }
    else if (result.isImaginary)
    {
        // Roots are imaginary - 
        // So root 1 contains -b/2a and root 2 contains sqrt(-d)/2a
        printf("Quadratic equation %dx^2%+dx%+d = 0 has complex roots : ",a,b,c);
        printf("[ %.2f%+.2fi, %.2f%+.2fi]\n", result.root1,result.root2,result.root1,-result.root2);
    }
    else
    {
        printf("Roots of Quadratic equation %dx^2%+dx%+d = 0 are : ",a,b,c);
        printf("[ %.2f, %.2f] \n", result.root1, result.root2);
    }
return 0;
}

quadRoots solveQuadraticEq(int a, int b, int c)
{
    // Initialisations
    quadRoots roots = {0,0,0,0,""};
    float discriminant;
    
    // Value of a is 0 - meaning this is not quadratic equation.
    if (0 == a)
    {
        roots.errorCode = 1000;
        strcpy(roots.errorDescription, "Not a quadratic equation");
        return roots;
    }
    
    // discriminant = b^2 - 4*a*c
    discriminant = b*b - 4*a*c;
    
    if (discriminant == 0)      // Both roots are equal
    {
        roots.root1 = roots.root2 = -b/2.0*a;
    }
    else if (discriminant < 0// Roots are imaginary
    {
        roots.root1 = -b/(2.0*a);
        roots.root2 = sqrt(-discriminant)/(2.0*a);
        roots.isImaginary = 1;
    }
    else                        // Roots are real numbers
    {
        roots.root1 = (-b + sqrt(discriminant)) / (2.0*a);
        roots.root2 = (-b - sqrt(discriminant)) / (2.0*a);
    }
    return roots;

}

No comments:

Post a Comment