M.Chelm - 5 months ago 36

C Question

I have to write program that displays the nth roots of unity when given a positive integer n. It's a programming project 27.4 from K.N.King book on C programming.

my attempt:

`#include <stdio.h>`

#include <complex.h>

#include <math.h>

int main(void)

{

int n, k;

double complex nth;

printf("Enter positive integer: ");

scanf("%d", &n);

for (k = 0; k < n; k++) {

nth = exp(2 * M_PI * I * k / n);

printf("k = %d, %g + %g\n", k, creal(nth), cimag(nth));

}

return 0;

}

No matter what value of n I pass results are always the same. Can you give me some tips?

Answer

The `exp`

function expects a `double`

, but you pass it a `double complex`

.

Use `cexp`

instead:

```
nth = cexp(2 * M_PI * I * k / n);
```

Output:

```
Enter positive integer: 5
k = 0, 1 + 0
k = 1, 0.309017 + 0.951057
k = 2, -0.809017 + 0.587785
k = 3, -0.809017 + -0.587785
k = 4, 0.309017 + -0.951057
```