实现复数类
**
【问题描述】
实现复数类
add-复数相加
sub-复数相减
mul-复数相乘
div- 复数相除
【样例输入】
1 2 3 4
【样例输出】
c1: 1 + 2i
c2: 3 + 4i
c3: 0 + 0i
c1+c2 = 4 + 6i
c1-c2 = -2 + -2i
c1*c2 = -5 + 10i
c1/c2 = 0.44 + 0.08i
#include <iostream>
using namespace std;
class ComplexNumber
{
private:
double real,imaginary;
public:
ComplexNumber();
ComplexNumber(double ,double );
double Getreal();
double Getimaginary();
ComplexNumber add(ComplexNumber );
ComplexNumber sub(ComplexNumber );
ComplexNumber mul(ComplexNumber );
ComplexNumber div(ComplexNumber );
void output();
};
ComplexNumber::ComplexNumber()
{
cin>>real>>imaginary;
}
ComplexNumber::ComplexNumber(double r,double i)
{
real=r;
imaginary=i;
}
double ComplexNumber::Getreal()
{
return real;
}
double ComplexNumber::Getimaginary()
{
return imaginary;
}
ComplexNumber ComplexNumber:: add(ComplexNumber cn)
{
ComplexNumber c;
c.real=real+cn.real;
c.imaginary=imaginary+cn.imaginary;
return c;
}
ComplexNumber ComplexNumber:: sub(ComplexNumber cn)
{
ComplexNumber c;
c.real=real-cn.real;
c.imaginary=imaginary-cn.imaginary;
return c;
}
ComplexNumber ComplexNumber:: mul(ComplexNumber cn)
{
ComplexNumber c;
c.real=real*cn.real-imaginary*cn.imaginary;
c.imaginary=imaginary*cn.real+real*cn.imaginary;
return c;
}
ComplexNumber ComplexNumber:: div(ComplexNumber cn)
{
ComplexNumber c;
c.real=(real*cn.real+imaginary*cn.imaginary)/(cn.real*cn.real+cn.imaginary*cn.imaginary);
c.imaginary=(imaginary*cn.real-real*cn.imaginary)/(cn.real*cn.real+cn.imaginary*cn.imaginary);
return c;
}
void ComplexNumber::output()
{
cout<<real<<" + "<<imaginary<<"i"<<endl;
}
int main()
{
ComplexNumber c3(0,0);
ComplexNumber c1,c2;
cout<<"c1: ";
c1.output();
cout<<"c2: ";
c2.output();
cout<<"c3: ";
c3.output();
c3=c1.add(c2);
cout<<"c1+c2 = ";
c3.output();
c3=c1.sub(c2);
cout<<"c1-c2 = ";
c3.output();
c3=c1.mul(c2);
cout<<"c1*c2 = ";
c3.output();
c3=c1.div(c2);
cout<<"c1/c2 = ";
c3.output();
return 0;
}