1784_C语言实现常用的复数运算

全部学习汇总: GitHub - GreyZhang/c_basic: little bits of c.

这是最近学习的C语言数据结构的中的案例,但是没有给出具体的实现代码。根据自己的学习水平简单编写了一下,倒是能够计算与输出,但是不知道还有没有什么缺陷。

借用到了部分之前博客中展示的代码,以下是今天实现的核心代码:

#include "complex.h"

#include "complexp.h"

CPX_NUM_p_t CPX_compute_sum(CPX_NUM_p_t cpx1,CPX_NUM_p_t cpx2)

{

    CPX_NUM_p_t cpx_sum = CDA_NEW(CPX_NUM_t);

    cpx_sum->real = cpx1->real + cpx2->real;

    cpx_sum->imaginary = cpx1->imaginary + cpx2->imaginary;

        

    return cpx_sum;

}

CPX_NUM_p_t CPX_compute_diff(CPX_NUM_p_t cpx1,CPX_NUM_p_t cpx2)

{

         CPX_NUM_p_t cpx_diff = CDA_NEW(CPX_NUM_t);

         cpx_diff->real = cpx1->real - cpx2->real;

         cpx_diff->imaginary = cpx1->imaginary - cpx2->imaginary;

         return cpx_diff;

}

CPX_NUM_p_t CPX_compute_neg(CPX_NUM_p_t cpx)

{

         CPX_NUM_p_t result = CDA_NEW(CPX_NUM_t);

         result->real = -cpx->real;

         result->imaginary = -cpx->imaginary;

         return result;

}

CPX_NUM_p_t CPX_compute_prod(CPX_NUM_p_t cpx1,CPX_NUM_p_t cpx2)

{

         CPX_NUM_p_t prod = CDA_NEW(CPX_NUM_t);

         prod->real = cpx1->real * cpx2->real - cpx1->imaginary * cpx2->imaginary;

         prod->imaginary = cpx1->imaginary * cpx2->real + cpx1->real * cpx2->imaginary;

         return prod;

}

CPX_NUM_p_t CPX_compute_quot(CPX_NUM_p_t cpx1,CPX_NUM_p_t cpx2)

{

         CPX_NUM_p_t quot = CDA_NEW(CPX_NUM_t);

         double a,b,c,d;

         a = cpx1->real;

         b = cpx1->imaginary;

         c = cpx2->real;

         d = cpx2->imaginary;

         quot->real = (a * c + b * d)/(c * c + d * d);

         quot->imaginary = (b * c - a * d)/(c * c + d *d);

         return quot;

}

主函数以及简单的测试接口代码:

#include "stdio.h"

#include "cda.h"

#include "complex.h"

int main(void)

{

    CPX_NUM_t complex_num1;

    CPX_NUM_t complex_num2;

    CPX_NUM_t result;

    complex_num1.real = 123;

    complex_num1.imaginary = 234;

    complex_num2.real = 345;

    complex_num2.imaginary = 456;

        

    result = *CPX_compute_sum(&complex_num1,&complex_num2);

         printf("For Sum reuslt is:(%lf,%lfi)\n",result.real,result.imaginary);

         result = *CPX_compute_diff(&complex_num1,&complex_num2);

    printf("For Diff reuslt is:(%lf,%lfi)\n",result.real,result.imaginary);

         result = *CPX_compute_neg(&complex_num1);

         printf("For Neg reuslt is:(%lf,%lfi)\n",result.real,result.imaginary);

         result = *CPX_compute_prod(&complex_num1,&complex_num2);

         printf("For Prod reuslt is:(%lf,%lfi)\n",result.real,result.imaginary);

         result = *CPX_compute_quot(&complex_num1,&complex_num2);

         printf("For Quot reuslt is:(%lf,%lfi)\n",result.real,result.imaginary);

        

    return 0;

}

编译以及运行结果:

1784_C语言实现常用的复数运算_第1张图片

你可能感兴趣的:(C,c语言,开发语言)