Santhosh Pai
Santhosh Pai

Reputation: 2625

Issues working with complex.h

I have written a small c code to find the sqrt of a number . And i want the program to even find the sqrt of a negative number . I came across complex.h and couple of functions to perform the complex arithmetic .I have made use of them and i'm getting a couple of warning messages while compiling.The code does not calculate the square root of positive and negative numbers correctly .

1)What is the correct format specifier for printf and scanf for printing and taking in complex numbers ? Please let me know where exactly i'm going wrong .I'm using a gcc compiler and OS is Ubuntu 12.04 LTS.I have attached the code and the outputs.

    #include <stdio.h>
    #include <math.h>
    #include <complex.h>


    int main()
    {
      float complex var,op;
      printf(" Enter the number : " );
      scanf("%lf",&var);
      op=csqrt(var);
      printf("%lf \n",op);
    }

    o/p Enter the number : 4
        0.011604
    Another o/p Enter the number : -4
        -0.011604

Upvotes: 1

Views: 1413

Answers (3)

Deepu
Deepu

Reputation: 7610

To find the square root of a negative number you can use the following code,

  printf(" Enter the number : " );
  scanf("%lf",&var);
  if(var < 0)
  {
     op=csqrt(-var);
     printf("The square root is %lfi \n",op);
  }
  else
  {
     op=csqrt(var);
     printf("The square root is %lf \n",op);
  }

Upvotes: 1

Dave
Dave

Reputation: 46249

printf and scanf don't have native support for complex numbers, but that's OK; you can write the format easily enough:

scanf( "%f %fi", &re, &im );

now re and im contain the real and imaginary parts (although it won't accept spaces after the + or -, so 3 + 2i will be rejected, but 3 +2i and 3+2i are fine.

The same goes for printing;

printf( "%f%+fi", re, im );

will print the variables in 3+2i form.

Finally, though it doesn't seem to be directly part of your question, the square root of a negative number is simply the square root of the positive value multiplied by i.

Upvotes: 1

Michael Burr
Michael Burr

Reputation: 340198

From C99:

6.2.5/13 Types

Each complex type has the same representation and alignment requirements as an array type containing exactly two elements of the corresponding real type; the first element is equal to the real part, and the second element to the imaginary part, of the complex number.

So as one possibility, you can use:

scanf("%f %f",&var[0], &var[1]);

To read in a float complex type, with whitespace separating the real and imaginary parts.

Upvotes: 2

Related Questions