Home > Net >  complex number calculator: arithmetic operations with struct variables in c
complex number calculator: arithmetic operations with struct variables in c

Time:10-29

Trying to write a c program that can do complex number calculations. The program has to use this structure:

typedef struct Complex_ {
    double RealPart;
    double ImagPart;
} Complex;

It has to use one function to read in user inputs for the complex numbers, and another function to add them, another to multiply them, etc. I'm trying to get the function to add the numbers right now, and I'm trying to figure out how to do this.This is the function for reading in the user input:

Complex read_complex(void) {
    Complex user1, user2;
    printf("Enter first complex number: ");
    scanf("%lf %lf", &user1.RealPart, &user1.ImagPart);
    printf("Enter the second complex number: ");
    scanf("%lf %lf", &user2.RealPart, &user2.ImagPart);

return;

}

And this is what I have so far for adding the complex numbers:

Complex add_complex(Complex z1, Complex z2) {
    Complex z3;

    z3 = z1   z2;//error on this line

    return(z3);

}

The function has to return z3, and z3 needs to equal z1 z2, and z1 and z2 have to be variables of type Complex. I'm not sure how to make it work with these specifications since you can't do arithmetic operations with struct variables.

CodePudding user response:

You can't add or substract the data structures.

Complex add_complex(Complex z1, Complex z2) {
    Complex z3;

    z3.RealPart = z1.RealPart   z2.RealPart;
    z3.ImagPart = z1.ImagPart   z2.ImagPart;

    return(z3);
}

CodePudding user response:

Not what you're asking about, but your read_complex function as shown won't work. Suggest changing to something like the following

#include <stdbool.h>

bool read_complex(Complex* user1, Complex* user2)
{
  bool inputValid = false;
  
  // weak check for validity, a non-NULL pointer isn't necessarily
  // valid. In fact, probably better to skip this check and instead
  // document/accept UB if user1 and/or user2 are not valid pointers.
  if (user1 != NULL && user2 != NULL)
  {
    printf("Enter first complex number: ");
    if (scanf("%lf %lf", &(user1->RealPart), &(user1->ImagPart)) == 2)
    {
      printf("Enter the second complex number: ");
      if (scanf("%lf %lf", &(user2->RealPart), &(user2->ImagPart)) == 2)
      {
        inputValid = true;
      } // else, print error message?
    } // else, print error message?
  }

  return inputValid;
}

scanf returns an int indicating the number of inputs that matched the supplied format specifiers. That should be 2 for each input, if not, you know there's a problem. The caller of read_complex can decide what to do next if it returns false.

  • Related