【C语言】【结构体】复数类型加减乘除的实现

博客内查看此文章效果更好


/*
编写人:naruuu
编写类型:复数类型实现 
编写时间:2020 9 20
要点:有能计算复数类型的数学基础 
本代码主要构建于建立结构体的基础之上利用结构体进行运算。
*/
typedef struct complex//构建复数的结构体类型(包含数部和虚部)
{
	float Realpart;
	float Imagepart;
}Complex;
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)//加法运算
{
	Complex sum;
	sum.Realpart=c1.Realpart+c2.Realpart;
	sum.Imagepart=c1.Imagepart+c2.Imagepart;
	return sum;
}
Complex Sub(Complex c1,Complex c2)//减法运算
{
	Complex dif;
	dif.Realpart=c1.Realpart-c2.Realpart;
	dif.Imagepart=c1.Imagepart-c2.Imagepart;
	return dif;
}
Complex Mul(Complex c1,Complex c2)//乘法运算
{
	Complex cheng;
	cheng.Realpart=c1.Realpart*c2.Realpart-c1.Imagepart*c2.Imagepart;
	cheng.Imagepart=c1.Realpart*c2.Imagepart+c1.Imagepart*c2.Realpart;
	return cheng;
}
Complex Div(Complex c1,Complex c2)//除法运算
{
	Complex chu;
	chu.Realpart=(c1.Realpart*c2.Realpart+c1.Imagepart*c2.Imagepart)/(c2.Realpart*c2.Realpart+c2.Imagepart*c2.Imagepart);
	chu.Imagepart=(c1.Imagepart*c2.Realpart-c1.Realpart*c2.Imagepart)/(c2.Realpart*c2.Realpart+c2.Imagepart*c2.Imagepart);
	if((c2.Realpart*c2.Realpart+c2.Imagepart*c2.Imagepart)==0)
		printf("the num doesnt exist");
	else
	return chu;
}
void Show(Complex c)//复数类型的表示方法
{
	if(c.Realpart!=0&&c.Imagepart!=0)
	printf("%.2f+%.2fi",c.Realpart,c.Imagepart);
	else if(c.Realpart!=0&&c.Imagepart==0)
	printf("%.2f",c.Realpart);
	else if(c.Realpart==0&&c.Imagepart!=0)
	printf("%.2fi",c.Imagepart);
	else if(c.Realpart==0&&c.Imagepart==0)
	printf("%d",0);
} 
static void helpTestShow(Complex C1,Complex C2)
{
	Show(C1);printf("\n");Show(C2);printf("\n");
	printf("he:");Show(Add(C1,C2));printf("\n");
	printf("cha:");Show(Sub(C1,C2));printf("\n");
	printf("ji:");Show(Mul(C1,C2));printf("\n");
	printf("shang:");Show(Div(C1,C2));printf("\n\n");
}
void TestComplex()//测试代码
{
	Complex C1,C2;
	Create(C1,520,0);Create(C2,1314,0);helpTestShow(C1,C2);
	Create(C1,0.5,0.7);Create(C2,0.5,-0.7);helpTestShow(C1,C2);
	Create(C1,-8,0);Create(C2,0,10);helpTestShow(C1,C2);
	Create(C1,0,0);Create(C2,0,-90);helpTestShow(C1,C2);
	Create(C1,2,3);Create(C2,4,-9);helpTestShow(C1,C2);

}
main()
{
	TestComplex();
}
/*测试数据结果
520.00
1314.00
he:1834.00
cha:-794.00
ji:683280.00
shang:0.40

0.50+0.70i
0.50+-0.70i
he:1.00
cha:1.40i
ji:0.74
shang:-0.32+0.95i

-8.00
10.00i
he:-8.00+10.00i
cha:-8.00+-10.00i
ji:-80.00i
shang:0.80i

0
-90.00i
he:-90.00i
cha:90.00i
ji:0
shang:0

2.00+3.00i
4.00+-9.00i
he:6.00+-6.00i
cha:-2.00+12.00i
ji:35.00+-6.00i
shang:-0.20+0.31i

	*/ 

你可能感兴趣的:(c语言,线性代数)