数据结构(C语言版)(第二版)类C的C实现(1)--------复数

目录

        • 前言
        • 源代码

前言

马马虎虎学了学C,想着终于可以尝试学一下数据结构了,结果发现学着还是那么费劲,可能还是代码写的太少,而且想把一个抽象数据类型转换成可以运行的C程序对我这个小白来说简直就跟做项目一样。不过还是能一点一点写完的。在这里给大家分享出来,欢迎大家交流指正。

源代码

#include 

typedef struct
{
    float Realpart;
    float Imagepart;
} Complex;

void Create(Complex *C, float x, float y);
/*
这里卡了一阵,书上的"&Complex C"是C++中的引用调用的参数传递,
C是没有这种用法的,所以这里使用指针来实现。
*/
float GetReal(Complex C); //获取复数的实部
float GetImage(Complex C); //获取复数的虚部
Complex Add(Complex C1, Complex C2); //加法
Complex Sub(Complex C1, Complex C2); //减法
Complex Mul(Complex C1, Complex C2); //乘法
Complex Div(Complex C1, Complex C2); //除法

int main(int argc, char const *argv[])
{
    Complex A, B;
    Complex *pA = &A, *pB = &B;
    //为了方便这里就直接传数了,感兴趣的朋友可以改成带输入的,就可以当工具用了。
    Create(pA, 2.0, 3.0); 
    Create(pB, 3.0, 4.0);
    Complex C = Add(A, B);
    Complex D = Sub(A, B);
    Complex E = Mul(A, B);
    Complex F = Div(A, B);

    printf("A: %.1f + %.1fi\n", GetReal(A), GetImage(A));
    printf("B: %.1f + %.1fi\n", GetReal(B), GetImage(B));
    printf("A+B: %.1f + %.1fi\n", GetReal(C), GetImage(C));
    printf("A-B: %.1f + %.1fi\n", GetReal(D), GetImage(D));
    printf("A*B: %.1f + %.1fi\n", GetReal(E), GetImage(E));
    printf("A/B: %.1f + %.1fi\n", GetReal(F), GetImage(F));
    return 0;
}

void Create(Complex *C, float x, float y)
{
    C->Realpart = x;
    C->Imagepart = y;
}

float GetReal(Complex C)
{
    return C.Realpart;
}

float GetImage(Complex C)
{
    return C.Imagepart;
}

Complex Add(Complex C1, Complex C2) 
//(a+bi)+(c+di) = (a+b)+(c+d)i
{
    Complex added;
    added.Realpart = C1.Realpart + C2.Realpart;
    added.Imagepart = C1.Imagepart + C2.Imagepart;
    return added;
}

Complex Sub(Complex C1, Complex C2) 
//(a+bi)-(c+di) = (a-b)+(c-d)i
{
    Complex subed;
    subed.Realpart = C1.Realpart - C2.Realpart;
    subed.Imagepart = C1.Imagepart - C2.Imagepart;
    return subed;
}

Complex Mul(Complex C1, Complex C2)
//(a+bi)(c+di) = (ac-bd) + (bc+ad)i
{
    Complex muled;
    muled.Realpart = (C1.Realpart * C2.Realpart) - (C1.Imagepart * C2.Imagepart);
    muled.Imagepart = (C1.Imagepart * C2.Realpart) + (C1.Realpart * C2.Imagepart);
    return muled;
}

Complex Div(Complex C1, Complex C2)
//(a+bi)/(c+di) = (ac+bd)/(c^2+d^2)+((bc-ad)/(c^2+d^2))i
{
    Complex dived;
    dived.Realpart = (C1.Realpart * C2.Realpart) + (C1.Imagepart * C2.Imagepart) / 
    (C2.Realpart * C2.Realpart + C2.Imagepart * C2.Imagepart);
    dived.Imagepart = (C1.Imagepart * C2.Realpart) - (C1.Realpart * C2.Imagepart) / 
    (C2.Realpart * C2.Realpart + C2.Imagepart * C2.Imagepart);
    return dived;
}

你可能感兴趣的:(c语言,数据结构,c语言,数据结构)