讨论/技术交流/C语言复数的加减乘除/
C语言复数的加减乘除

写了个用c语言进行复数加减乘除运算的代码,各位大佬看看有哪里可以改进。
#include<iostream.h>
typedef struct
{
double real;
double imag;

}Complex;

void InitComplex(Complex *&z)//开辟空间
{
z=new Complex;
}

void DestoryComplex(Complex *&z)//销毁
{
delete z;
}

void AssignComplex(Complex *&z,double v1,double v2)//构造一个复数
{
z=new Complex;
z->real=v1;
z->imag=v2;
}

void DispComplex(Complex *z)//打印复数
{
if(z->real==0)
{
if(z->imag==0)
cout<<"0"<<endl;
else
{
if(z->imag>0&&z->imag!=1)
cout<<z->imag<<"i"<<endl;
if(z->imag==1)
cout<<"i"<<endl;
if(z->imag<0&&z->imag!=-1)
cout<<z->imag<<"i"<<endl;
if(z->imag==-1)
cout<<"-i"<<endl;

}

}
else
{
if(z->imag==0)
cout<<z->real<<endl;
else
{
if(z->imag>0&&z->imag!=1)
cout<<z->real<<"+"<<z->imag<<"i"<<endl;
if(z->imag==1)
cout<<z->real<<"+"<<"i"<<endl;
if(z->imag<0&&z->imag!=-1)
cout<<z->real<<z->imag<<"i"<<endl;
if(z->imag==-1)
cout<<z->real<<"-i"<<endl;
}
}

}
void Add(Complex *z1,Complex *z2,Complex *&sum)//加
{
sum->real=z1->real+z2->real;
sum->imag=z1->imag+z2->imag;
cout<<"两个复数的和为:";
DispComplex(sum);
}
void Jian(Complex *z1,Complex *z2,Complex &difference)//减
{
difference->real=z1->real-z2->real;
difference->imag=z1->imag-z2->imag;
cout<<"两个复数的差为:";
DispComplex(difference);
}
void Cheng(Complex z1,Complex z2,Complex &r)//乘
{
r->real=z1->real
z2->real-z1->imag
z2->imag;
r->imag=z1->real
z2->imag+z1->imag
z2->real;
cout<<"两个复数的积为:";
DispComplex(r);
}
void Chu(Complex *z1,Complex *z2,Complex *&r)//除
{

if(z2->real==0&&z2->imag==0)
cout<<"除数不能为0";
else
{
r->real=(z1->realz2->real-z1->imagz2->imag*-1)/(z2->realz2->real+z2->imagz2->imag);
r->imag=(z1->realz2->imag-1+z1->imagz2->real)/(z2->realz2->real+z2->imag*z2->imag);
cout<<"两个复数的商为:";
DispComplex(r);
}
}

void main()
{
Complex *z1,*z2,*z3,*z4,*z5,*z6;
double a,b;
cout<<"请输入第一个复数的实部:";
cin>>a;
cout<<"请输入第一个复数的虚部:";
cin>>b;

AssignComplex(z1,a,b);
cout<<"第一个复数为:";
DispComplex(z1);

cout<<"请输入第二个复数的实部:";
cin>>a;
cout<<"请输入第二个复数的虚部:";
cin>>b;

AssignComplex(z2,a,b);
cout<<"第二个复数为:";
DispComplex(z2);
InitComplex(z3);
InitComplex(z4);
InitComplex(z5);
InitComplex(z6);
Add(z1,z2,z3);
Jian(z1,z2,z4);
Cheng(z1,z2,z5);
Chu(z1,z2,z6);

}

共 0 个回复
暂无回复