定义复数类Complex,使用友元,完成复数的加法、减法、乘法、除法运算,以及对复
数的输出。
直接上代码:
#include "iostream"
using namespace std;
class complex
{
private:
int real,image;
public:
complex(){
}
complex(int r,int i)
{
real=r;image=i;
}
friend class A;
friend void show(complex c);
};
class A
{
public:
complex sub(complex &c1,complex &c2);
complex add(complex &c1,complex &c2);
complex mul(complex &c1,complex &c2);
complex div(complex &c1,complex &c2);
};
complex A::add(complex &c1,complex &c2)
{
complex c;
c.real=c1.real+c2.real;
c.image=c1.image+c2.image;
return c;
}
complex A::sub(complex &c1,complex &c2)
{
complex c;
c.real=c1.real-c2.real;
c.image=c1.image-c2.image;
return c;
}
complex A::mul(complex &c1,complex &c2)
{
complex c;
c.real=c1.real*c2.real-c1.image*c2.image;
c.image=c1.real*c2.image+c1.image*c2.real;
return c;
}
complex A::div(complex &c1,complex &c2)
{
complex c;
int temp=c2.real*c2.real+c2.image*c2.image;
if(!temp)
{
cout<<"不能被0除"<<endl;
exit(-1);
}
c.real=(c1.real*c2.real+c1.image*c2.image)/temp;
c.image=(c1.image*c2.real-c2.image*c1.real)/temp;
return c;
}
void show (complex c)
{
cout<<"("<<c.real<<"+"<<c.image<<"i"<<")"<<endl;
}
int main()
{
int i,j,k,l;
char a;
cout<<"请输入第一个复数:"<<endl;
cin>>i>>j;
cout<<"请输入第二个复数:"<<endl;
cin>>k>>l;
cout<<"请输入运算符:"<<endl;
cin>>a;
complex c1(i,j);
complex c2(k,l);
A b;
if(a=='+')
{
c1=b.add(c1,c2);
show(c1);
}
if(a=='-')
{
c1=b.sub(c1,c2);
show(c1);
}
if(a=='*')
{
c1=b.mul(c1,c2);
show(c1);
}
if(a=='/')
{
c1=b.div(c1,c2);
show(c1);
}
system("pause");
return 0;
}
鄙人第一次写博客,肯定还有许多不足之处,希望大家多多指教,代码有哪里不懂的,欢迎在评论区提问!!!也欢迎各位帮我修正!!!