Search code examples
ccomplex-numbers

How to print the imaginary root of quadratic equation in c?


I need to print the imaginary root in the quadratic equation. but when I execute my code the result shows me that the imaginary root is 0.00000i. even I use to <complex.h> also same.

Can everybody help me to check the code that I bold?

//C program to find the root of the quadratic equation
#include<stdio.h>
#include<math.h>
#include<complex.h>

int main()
{
    double  a, b, c, x, x1, x2, disc, xr, ximg1, ximg2;
    
    printf("Please enter the value of quadratic equation, a: ");
    scanf("%lf", &a);
    printf("Please enter the value of quadratic equation, b: ");
    scanf("%lf", &b);
    printf("Please enter the value of quadratic equation, c: ");
    scanf("%lf", &c);

    if( a == 0 )
    {
        x = -(c/b);
        printf("\nThis is not a quadratic equation.\n");
        printf("x = %.3lf", x);
    }
    else{
    disc = (b*b) - 4*a*c;
        if( disc == 0 ){
             x1 = -b / 2 * a;
             x2 = -b / 2 * a;
             printf("x1 = %lf, x2 = %lf", x1, x2);
        }
        else if(disc > 0){
            x1 = ( -b + sqrt( disc ) ) / 2 * a;
            x2 = ( -b - sqrt( disc ) ) / 2 * a;
            printf("x1 = %.1lf, x2 = %.1lf", x1, x2);
        }
        else{
            ximg1 = sqrt( disc ) / 2 * a;
            ximg2 = - sqrt( disc ) / 2 * a;
            xr = - b / ( 2 * a );
            **printf("xr = %lf, ximg1 = %lfi, ximg2 = %lfi", crealf(xr), cimagf(ximg1), cimagf(ximg2));**
        }
    }

    return 0;
}

The output are shown as below:

Please enter the value of quadratic equation, a: 4
Please enter the value of quadratic equation, b: 1
Please enter the value of quadratic equation, c: 3
xr = -0.125000, ximg1 = 0.000000i, ximg2 = 0.000000i
Process returned 0 (0x0)   execution time : 3.914 s
Press any key to continue.

Solution

  • You should print the roots as complex numbers using the computed real and imaginary parts. No need for <complex.h> nor complex types:

        double xr = - b / ( 2 * a );
        double ximg1 = -sqrt( -disc ) / (2 * a);
        double ximg2 = -ximg1;
        printf("x1 = %lf%+lfi, x2 = %lf%+lfi\n", xr, ximg1, xr, ximg2);