【C语言】如何很好的实现复数类型

mac2024-06-17  38

首先声明:在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; }
最新回复(0)