摘要:C语言 数据结构 抽象数据类型 顺序结构
正文:用C语言来进行复数的抽象数据类型实现,代码如下:
#include<stdio.h>
#include<stdlib.h>
typedef struct Complex
{
float real;
float image;
}Complex;
int lnitComplex(Complex &C,float vr,float vi)
{
C.real=vr;
C.image=vi;
return 1;
}
void OutComplex(Complex &C)
{
printf("%f+%fi\n",C.real,C.image);
}
Complex AddComplex(Complex &add,Complex C1,Complex C2)
{
add.real=C1.real+C2.real;
add.image=C1.image+C2.image;
return add;
}
Complex SubComplex(Complex &sub,Complex C1,Complex C2)
{
sub.real=C1.real-C2.real;
sub.image=C1.image-C2.image;
return sub;
}
Complex MulComplex(Complex &mul,Complex C1,Complex C2)
{
mul.real=((C1.real*C2.real)-(C1.image*C2.image));
mul.image=((C1.real*C2.image)+(C1.image*C2.real));
return mul;
}
int main()
{
int choice;
Complex C,add,sub,mul,C1,C2;
float a,b,a1,b1;
printf("********************\n");
printf("1.输入复数C1\n");
printf("2.输入复数C2\n");
printf("3.输出复数C1\n");
printf("4.输出复数C2\n");
printf("5.C1和C2的和为\n");
printf("6.C1和C2的差为\n");
printf("7.C1和C2的积为\n");
printf("0.结束程序\n");
printf("********************\n");
for(;;)
{
scanf("%d",&choice);
switch(choice)
{
case 1:
scanf("%f,%f",&a,&b);
if(b==0)
{
printf("虚部不能为0");
exit(0);
}
else
{
lnitComplex(C1,a,b);
printf("输入完成\n");
}
break;
case 2:
scanf("%f,%f",&a1,&b1);
if(b==0)
{
printf("虚部不能为0\n");
exit(0);
}
else
{
lnitComplex(C2,a,b);
printf("输入完成\n");
}
break;
case 3:
OutComplex(C1);
break;
case 4:
OutComplex(C2);
break;
case 5:
AddComplex(add,C1,C2);
OutComplex(add);
break;
case 6:
SubComplex(sub,C1,C2);
OutComplex(sub);
break;
case 7:
MulComplex(mul,C1,C2);
OutComplex(mul);
break;
case 0:
exit(0);
}
}
return 0;
}
编译结果如图: