#include <stdio.h>
#include <math.h>
typedef struct { //构建复数的结构体类型(包含实部和虚部)
float realpart;
float imagpart;
} Complex;
// 函数声明
Complex assign(float real,float imag); //赋值
Complex add(Complex C1 ,Complex C2); //+
Complex minus(Complex C1 ,Complex C2); //-
Complex multiply(Complex C1 ,Complex C2);//*
Complex divide(Complex C1 ,Complex C2);// /
void Show(Complex C);//输出复数类型
int main() {
Complex z1,z2,z3,z4,z;
z1=assign(8.0,6.0);
z2=assign(4.0,3.0);
z3=multiply(z1,z2);
z4=add(z1,z2);
z=divide(z3,z4);
Show(z);
return 0;
}
Complex assign(float real,float imag) {
Complex C;
C.realpart = real; //实部赋值
C.imagpart = imag; //虚部赋值
return C;
}
Complex add(Complex C1 ,Complex C2) { //加法
Complex C;
C.realpart = C1.realpart + C2.realpart;
C.imagpart = C1.imagpart + C2.imagpart;
return C;
}
Complex minus(Complex C1 ,Complex C2) { //减法
Complex C;
C.realpart = C1.realpart - C2.realpart;
C.imagpart = C1.imagpart - C2.imagpart;
return C;
}
Complex multiply(Complex C1 ,Complex C2) { //乘法
Complex C;
C.realpart = C1.realpart * C2.realpart - C1.imagpart * C2.imagpart;
C.imagpart = C1.imagpart * C2.realpart + C1.realpart * C2.imagpart;
return C;
}
Complex divide(Complex C1 ,Complex C2) { //除法
Complex C;
if(pow(C2.realpart,2) + pow(C2.imagpart,2) != 0) {
C.realpart = (C1.realpart * C2.realpart + C1.imagpart * C2.imagpart) / pow(C2.realpart,2) + pow(C2.imagpart,2);
C.imagpart = (C1.imagpart * C2.realpart - C1.realpart * C2.imagpart) / pow(C2.realpart,2) + pow(C2.imagpart,2);
} else {
printf("结果不存在");
}
return C;
}
void Show(Complex C) { //输出复数类型
if(C.realpart != 0 && C.imagpart != 0)
printf("%.2f+%.2fi",C.realpart,C.imagpart);
else if(C.realpart != 0 && C.imagpart == 0)
printf("%.2f",C.realpart);
else if(C.realpart == 0 && C.imagpart != 0)
printf("%.2fi",C.imagpart);
else if(C.realpart == 0 && C.imagpart == 0)
printf("%d",0);
}