The reason that calling creal
does not work is that either you have not included the proper header complex.h
or you are calling it with an argument x1
that is not of the correct type double complex
. The second error, when you call x1.real()
is because the .
notation tries to access a member of a struct
but x1
is a double.
I suggest using complex.h
that enables working with complex numbers and define a new abc-formula that deals with complex numbers. Also note that you can not use 'regular' math functions like sqrt
on variables of complex type but need to use the complex.h
analogs e.g. csqrt()
#include <complex.h>
int main(void)
{
double complex z = 1.0 + 0.5 * I;
printf("The real part of z = %f\n", creal(z));
printf("The iamginary part of z = %f\n", cimag(z));
return 0;
}
Edit:
completely redefine your function, try something like this:
void complex_abc() {
double complex a = 1;
double complex b = 2;
double complex c = 3;
double complex x1;
double complex x2;
double complex d;
d = b*b - 4 * a * c;
x1 = ( -b + csqrt(d) ) / 2*a;
x2 = ( -b - csqrt(d) ) / 2*a;
printf("x1 = %f + i %f\n", creal(x1), cimag(x1));
printf("x2 = %f + i %f\n", creal(x2), cimag(x2));
return;
}
And as correctly noted by @Lutzl in the comments you need to link the math library with the flag -lm
during compiling