抽象数据类型复数的求和求差实现(c语言)

#include
typedef struct
{
    float Realpart; //实部
    float Imagepart; //虚部
}Complex;

Complex Create(float x,float y)
{
    //构造一个复数
    Complex C;
    C.Realpart=x;
    C.Imagepart=y;
    return C;
}

float GetReal(Complex C)
{
    //取复数C=x+yi的实部
    return C.Realpart;
}

float GetImag(Complex C)
{
    //取复数C=x+yi的虚部
    return C.Imagepart;
}

Complex Add(Complex C1,Complex C2)
{
    //求两个复数C1和C2的和sum
    Complex sum;
    sum.Realpart=C1.Realpart+C2.Realpart;
    sum.Imagepart=C1.Imagepart+C2.Imagepart;
    return sum;
}

Complex Sub(Complex C1,Complex C2)
{
    //求两个复数C1和C2的差difference
    Complex difference;
    difference.Realpart=C1.Realpart-C2.Realpart;
    difference.Imagepart=C1.Imagepart-C2.Imagepart;
    return difference;
}

int main ()
{
    float a,b,c,d;
    char e;
    Complex C1,C2,C3;

    //输入第一组复数中的a和b
    printf("请输入复数C1的实部和虚部a和b(用空格隔开):");
    scanf("%f %f",&a,&b);
    C1=Create(a,b);

    //输入第二组复数中的c和d
    printf("请输入复数C2的实部和虚部c和d(用空格隔开):");
    scanf("%f %f",&c,&d);
    C2=Create(c,d);

    //进行相加或相减操作
    printf("请选择加法或是减法(+/-):");
    getchar();
    scanf("%c",&e);
    if(e=='+')
        C3=Add(C1,C2);
    if(e=='-')
        C3=Sub(C1,C2);

    //输出结果
    printf("两个复数的和/差为: %f+%fi",C3.Realpart,C3.Imagepart);
    return 0;
}

 

你可能感兴趣的:(C,Language,Data,Structure)