您的位置:首页 > 理论基础 > 数据结构算法

<数据结构>复数四则运算

2016-12-28 15:51 351 查看
#include <iostream>
using namespace std;
//之所以用类模板  是因为输入不知道类型
template<class Elem>class Complex{
private:
Elem reality;
Elem falsehood;
public:
Complex(Elem r, Elem f){
reality = r;
falsehood = f;
}
~Complex(){
}
Complex operator + (const Complex& c1){
return Complex(reality + c1.reality, falsehood + c1.falsehood);
}
Complex operator - (const Complex& c1){
return Complex(reality - c1.reality, falsehood + c1.falsehood);
}
Complex operator * (const Complex& c1){
return Complex(reality*c1.reality - falsehood*c1.falsehood, reality*c1.falsehood + falsehood*c1.reality);
}
Complex operator / (const Complex& c1){
if (falsehood != 0)
return Complex((reality * c1.reality + falsehood + c1.falsehood) / (c1.reality*c1.reality + c1.falsehood * c1.falsehood), (falsehood * c1.reality - reality * c1.falsehood) / (c1.reality * c1.reality + c1.falsehood * c1.falsehood));
else
cout << "分母不能为0,请重新输入" << endl;
}
Elem Reality(){
return reality;
}
Elem Falsehood(){
return falsehood;
}
void Conjugate(){
falsehood = -falsehood;
}
void Output(){
if (falsehood>0)
{
cout << "(" << reality << "+" << falsehood << "i" << ")" << endl;
}
else
cout << "(" << reality << falsehood << "i" << ")" << endl;
}
};

int main() //测试
{

float a, b, c, d;
cin >> a >> b >> c >> d;
Complex<float> c1(a, b);
Complex<float> c2(c, d);
cout << "测试结果:" << endl;
cout << "两个复数分别为:(1+2i)和(2+3i)" << endl;
cout << "(1+2i)+(2+3i)=";
(c1 + c2).Output();
cout << "\n(1+2i)-(2+3i)=";
(c1 - c2).Output();
cout << "\n(1+2i)*(2+3i)=";
(c1*c2).Output();
cout << "\n(1+2i)/(2+3i)=";
(c1 / c2).Output();
cout << "\nc1的实部是:" << c1.Reality() << endl;
cout << "\nc1的虚部是:" << c1.Falsehood() << endl;
cout << "\nc2的实部是:" << c2.Reality() << endl;
cout << "\nc2的虚部是:" << c2.Falsehood() << endl;
cout << "\nc1的共轭复数是:";
c1.Conjugate();
c1.Output();
cout << "\nc2的共轭复数是:";
c2.Conjugate();
c2.Output();
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: