beginner - 8 months ago 37

C Question

I am studying for an Intro to C test that requires me to write functions that involve structs. The question only asks me to write the function, but I want to write an entire code that runs so I can put in numbers and see if my code is running properly. I think I wrote the function properly, I just don't know how to code numbers in and have it print out the numbers.

This is the question.

Here is what I've written for the above question.

`struct complex_numb Add_Complex(struct complex_numb C1, struct complex_numb C2){`

struct complex_numb C3;

C3.real = C1.real + C2.real;

C3.imaginary = C1.imaginary + C2.imaginary;

return (C3);

};

We aren't using typedef yet.

I thought it would be something like this, but it isnt working.

`#include <stdio.h>`

struct complex_numb Add_Complex(struct complex_numb C1, struct complex_numb C2);

int main(){

struct complex_numb{

float real;

float imaginary;

};

Add_Complex(1,2,3,4);

printf("%f %f", C3.real, C3.imaginary);

}

struct complex_numb Add_Complex(struct complex_numb C1, struct complex_numb C2){

struct complex_numb C3;

C3.real = C1.real + C2.real;

C3.imaginary = C1.imaginary + C2.imaginary;

return (C3);

};

Answer

Create your C1 and C2, add those values to the attributes inside your struct, and create your return object of complex_numb which called "C3" and have that = to the result of the function call that takes in C1 and C2. Changed your struct using typedef and moved it out of main. Here is a compiling and working version:

```
#include <stdio.h>
typedef struct {
float real;
float imaginary;
}complex_numb;
complex_numb Add_Complex(complex_numb C1, complex_numb C2);
int main()
{
complex_numb C1;
C1.real = 1;
C1.imaginary = 2;
complex_numb C2;
C2.real = 3;
C2.imaginary = 4;
//Add_Complex(1,2,3,4);
complex_numb C3;
C3 = Add_Complex(C1,C2);
printf("%f %f", C3.real, C3.imaginary);
}
complex_numb Add_Complex(complex_numb C1, complex_numb C2){
complex_numb C3;
C3.real = C1.real + C2.real;
C3.imaginary = C1.imaginary + C2.imaginary;
return (C3);
}
```

Source (Stackoverflow)