我有一段更大的代码(不是我写的),它使用了通过结构定义的复数。我需要对其进行编辑,并简单地将一个复数乘以一个实数,但似乎无法正确处理。我不断收到以下错误消息。
error: invalid operands to binary * (have ‘cplx’ and ‘double’)
我知道这可以使用 complex.h 库来完成,但这意味着需要大量重写,所以有更简单的方法吗?下面的代码重现了我的问题。
#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;
}
最佳答案
您首先必须使用 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;
}
如果你想通过将 c 乘以它的值来更新结构,它会遵循
#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;
}
希望这对您有所帮助!
关于c - C中的复数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42769100/