1

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

typedef struct COMPLEX_T
{
    int real;
    int imaginary;
} complex_t;  

else if (choice == 3) {
        printf("\n\nEnter a and  b where a + ib is a complex number\n");
        printf("a = ");
        scanf("%d", &a.real);
        printf("b = ");
        scanf("%d", &a.imaginary);
        float sqr_sum = pow(a.real, 2) + pow(a.imaginary, 2);
        float abs = pow(sqr_sum, 1/2);
        printf("\n\nThe absolute value is: %.2f", abs);
      } 

Here is a code snippet. I am trying to find the absolute value of a complex number. When I input two numbers the output is "1.00", no matter which two numbers I input.
Any suggestions?

Yunnosch
  • 26,130
  • 9
  • 42
  • 54
brun2
  • 13
  • 4
  • 2
    `1/2` ==> `1.0/2` otherwise it's integer division which yields `0`...or, maybe better, use `sqrt()` – pmg Oct 28 '20 at 18:31
  • Don't you get a "else without if error" for that code? Please provide a [mre]. – Yunnosch Oct 28 '20 at 18:38
  • @pmg I now realise that my answer is largely your comment. Do you want me to delete? But then you please make an answer. If it is OK with you I would extend my answer to use all of your contribution (with credits). – Yunnosch Oct 28 '20 at 18:40

1 Answers1

1

1/2 is integer division and zero.
Aything to the power of zero is one.

Convert either the 1 or the 2 (or both) to double

pow(x, 1.0/2);
pow(x, 1/(double)2);

Also sqrt() is used more often.

sqrt(x);

You might even want to change the previous line. Using pow() for integers is not recommended, among other things because of
Is floating point math broken?
For integers raised to the power of especially two, consider

float sqr_sum = a.real * a.real + a.imaginary * a.imaginary;
Yunnosch
  • 26,130
  • 9
  • 42
  • 54
  • You editing your part into my answer (appreciated of course) let me forget my promise to attribute. Thanks for confirming that you are already happy. @pmg – Yunnosch Oct 28 '20 at 18:59