首先声明:在C99标准中已经支持了复数类型。
在此不谈论这个,想了解的可以直接去查一查,这里说一下实现复数类型及运算。其实也很简单,直接定义一个简单结构和相关的算数函数就OK了。
下面是实现过程:
#include "stdio.h"
#define Real(c) (c).real
#define Imag(c) (c).imag
typedef struct {
double real;
double imag;
}complex;
complex cpx_make(double real, double imag)
{
complex ret;
ret.real = real;
ret.imag = imag;
return ret;
}
complex cpx_add(complex a, complex b)
{
return cpx_make(Real(a) + Real(b), Imag(a) + Imag(b));
}
int main()
{
complex a = cpx_make(1, 2);
complex b = cpx_make(3, 4);
//亦可直接如下写法
printf("%f", cpx_add(cpx_make(1, 2), cpx_make(3, 4)));
return 0;
}