- 复数有两个部分组成:实数部分和虚数部分。复数的一种书写方式是:(3.0,4.0),
其中,3.0是实数部分,4.0是虚数部分。假设a=(A,Bi),c=(C,Di),则下面是一些复数运算。
加法:a+c=(A+C,(B+D)i)。
减法:a-c=(A-C,(B-D)i)。
乘法:ac=(AC-BD,(AD+B*C)i)。
乘法::xc=(xC,x*Di),其中x为实数。
共轭:~a=(A,-Bi)。
请定义一个复数类,以便下面的程序可以使用它来获得正确的结果。
#ifndef PE11_7_H_
#define PE11_7_H_
#include<iostream>
class Complex
{
private:
struct Complex_t
{
double a;
double bi;
};
double a;
double bi;
Complex_t comlex;
void SetComplex(void);
void SetABi(void);
public:
Complex(double a = 0, double bi = 0);
friend std::ostream& operator<<(std::ostream& os, const Complex& a);
friend std::istream& operator>>(std::istream& is, Complex& a);
Complex operator+(Complex& a);
Complex operator-(Complex& a);
Complex operator*(Complex& a);
friend Complex operator~(Complex& a);
friend Complex operator*(double n,Complex& a);
};
#endif // !1
#include"pe11_7.h"
#include<iostream>
using namespace std;
Complex::Complex(double a, double bi)
{
this->a = a;
this->bi = bi;
SetComplex();
}
void Complex::SetComplex(void)
{
this->comlex.a = this->a;
this->comlex.bi = this->bi;
}
void Complex::SetABi()
{
this->a = this->comlex.a;
this->bi = this->comlex.bi;
}
ostream& operator<<(ostream& os, const Complex& a)
{
os << "(" << a.a << "," << a.bi << "i)";
return os;
}
istream& operator>>(istream& is, Complex& a)
{
cout << "real: ";
is >> a.a;
if (!is)
{
is.ignore(numeric_limits<streamsize>::max(), '\n');
return (is);
}
cout << "imaginary: ";
is >> a.bi;
if (!is)
{
is.ignore(numeric_limits<streamsize>::max(), '\n');
}
return (is);
}
Complex Complex::operator+(Complex& a)
{
Complex temp;
temp.a = this->a + a.a;
temp.bi = this->bi + a.bi;
return temp;
}
Complex Complex::operator-(Complex& a)
{
Complex temp;
temp.a = this->a - a.a;
temp.bi = this->bi - a.bi;
return temp;
}
Complex Complex::operator*(Complex& a)
{
Complex temp;
temp.a = this->a * a.a - this->bi * a.bi;
temp.bi = this->a * a.bi + this->bi * a.a;
return temp;
}
Complex operator*(double n, Complex& a)
{
Complex temp;
temp.a = n*a.a;
temp.bi = n*a.bi;
return temp;
}
Complex operator~(Complex& a)
{
Complex temp;
temp.a = a.a;
temp.bi = -a.bi;
return temp;
}
#pragma region 练习7.cpp
/*
*/
#if 1
#include <iostream>
#include"pe11_7.h"
int main()
{
using namespace std;
Complex a(3.0, 4.0); //to avid confusion with complex.h
Complex c ;
cout << "Enter a complex number(q to quit):\n";
while (cin>>c)
{
cout << "C is " << c << "\n";
cout << "complex conjugate is " << ~c << "\n";
cout << "a is " << a << "\n";
cout << "a + c is " << a + c << "\n";
cout << "a - c is " << a - c << "\n";
cout << "a*c is " << a * c << "\n";
cout << "2*c is " << 2 * c << '\n';
cout << "Enter a complex number(q to quit):\n";
}
cout << "Done!\n";
return 0;
}
#endif
#pragma endregion
测试符合题目要求