【问题描述】定义复数类,实现+,-,*运算符,实现两个复数的加减乘运算. 【输入形式】输入两个复数的实部和虚部 【输出形式】提示信息:"please input two complex numbers:" 【样例输入】3? ?4?
? ? ? ? ? ? ? ? ? ? ?10? ?-2.9 【样例输出】please input two complex numbers:?3? 4?
? ? ? ? ? ? ? ? ? ? ???10? -2.9 (横线数据为输入数据)
? ? ? ? ? ? ? ? ? ? ?c1 is 3+4i
? ? ? ? ? ? ? ? ? ? ?c2 is 10-2.9i
?????????????????????c1+c2=13+1.1i
????????????????? ? ? c1-c2=-7+6.9i
????????????????????? c1*c2=41.6+31.3i?
//两个复数的加减乘运算
#include<iostream>
using namespace std;
class fs
{
private:
double real;
double vir;
public:
fs();
friend fs operator+(fs a1, fs a2);
friend fs operator-(fs a1, fs a2);
friend fs operator*(fs a1, fs a2);//重载加减乘运算
void input();//输入函数
void display();//输出函数
};
fs::fs()
{
real=0;
vir=0;
}
fs operator+(fs a1, fs a2)
{
fs a3;
a3.real=a1.real+a2.real;
a3.vir=a1.vir+a2.vir;
return a3;
}
fs operator-(fs a1, fs a2)
{
fs a3;
a3.real=a1.real-a2.real;
a3.vir=a1.vir-a2.vir;
return a3;
}
fs operator*(fs a1, fs a2)
{
fs a3;
a3.real=a1.real*a2.real-a1.vir*a2.vir;
a3.vir=a1.vir*a2.real+a1.real*a2.vir;
return a3;
}//重载加减乘运算
void fs::input()//输入函数
{
cin>>real>>vir;
}
void fs::display()//输出函数
{
if(real!=0)
{
if(vir>0)cout<<real<<"+"<<vir<<"i"<<endl;
if(vir==0)cout<<real<<endl;
if(vir<0)cout<<real<<vir<<"i"<<endl;
}
if(real==0)
{
if(vir>0)cout<<vir<<"i"<<endl;
if(vir==0)cout<<"0"<<endl;
if(vir<0)cout<<vir<<"i"<<endl;
}
}
int main()
{
fs c1,c2,c3,c4,c5;
cout<<"please input two complex numbers:"<<endl;
c1.input();
c2.input();
cout<<"c1 is ";
c1.display();
cout<<"c2 is ";
c2.display();
c3=c1+c2;
cout<<"c1+c2=";
c3.display();
c4=c1-c2;
cout<<"c1-c2=";
c4.display();
c5=c1*c2;
cout<<"c1*c2=";
c5.display();
return 0;
}
|