Reputation: 1208
I have a larger piece of code (I didn't write it) that makes use of complex numbers defined through a structure. I need to edit it and simply multiply a complex number by a real but cant seem to get it right. I keep getting the following error message.
error: invalid operands to binary * (have ‘cplx’ and ‘double’)
I know this could be done using the complex.h library but that would mean a lot of rewriting so is there a simpler way? The code below reproduces my problem.
#include <stdio.h>
#include <math.h>
typedef struct cplxS {
double re;
double im;
} cplx;
int main()
{
double a = 1.3;
cplx b = {1, 2};
c = a * b;
}
Upvotes: 1
Views: 499
Reputation: 1903
You will first have to initialize a node using malloc
#include <stdlib.c>
int main(){
double a = 1.3;
//initialize struct
struct cplxS* b = malloc(sizeof(struct cplxS));
//set values for b
b->re = 1;
b->im = 2;
//preform your multiplication
double c = a*(b->re); //value c with re
double d = a*(b->im); //value d with im
//free node memory
free(b);
b = NULL;
}
If you want to update the struct by multiplying c to its values, it would follow
#include <stdlib.c>
int main(){
double a = 1.3;
//initialize struct
struct cplxS* b = malloc(sizeof(struct cplxS));
//set values for b
b->re = 1;
b->im = 2;
//preform your multiplication
b->re = a*(b->re); //update b with a*re
b->im = a*(b->im); //value b with a*im
//free node memory
free(b);
b = NULL;
}
Hope this helps!
Upvotes: 1
Reputation: 2626
You need to either cast the double as a complex number, and use the complex multiplication function (which presumably exists, or could/should be written by overloading * operator)
int main()
{
double a = 1.3;
cplx a_c = {1.3, 0}
cplx b = {1, 2};
c = a_c * b;
}
or actually perform the multiplication, either by building a definition for multiplication of reals and complex numbers (not shown), or just doing it yourself.
int main()
{
double a = 1.3;
cplx b = {1, 2};
cplx c = {b.re*a, b.im*a};
}
Upvotes: 0