题目描述
定义一个复数类Complex,实现+、-、*、/、++(前置)、++(后置)的运算符重载
输入格式
输入共一行,四个浮点数,分别表示虚数q的实数部分和虚数部分和虚数w的实数部分和虚数部分
输出格式
输出共6行,分别输出q+w,q-w,q*w,q / w , q++ , ++w的值
输入输出样例
输入 #1 复制
4 3 2 1
输出 #1 复制
6.00+4.00i
2.00+2.00i
5.00+10.00i
2.20+0.40i
4.00+3.00i
3.00+1.00i
#include<iostream>
#include<iomanip>
using namespace std;
class Complex{
public:
Complex(){real = 0;image = 0;}
Complex(double r,double i){real = r;image = i;}
Complex operator+(Complex &c2);
Complex operator-(Complex &c2);
Complex operator*(Complex &c2);
Complex operator/(Complex &c2);
Complex operator++();
Complex operator++(int);
void display();
private:
double real;
double image;
};
int main(){
double q_real,q_image,w_real,w_image;
cin>>q_real>>q_image>>w_real>>w_image;
Complex c1(q_real,q_image),c2(w_real,w_image),c3;
c3 = c1 + c2;
c3.display();
c3 = c1 - c2;
c3.display();
c3 = c1 * c2;
c3.display();
c3 = c1 / c2;
c3.display();
c3 = c1++;
c3.display();
c3 = ++c2;
c3.display();
return 0;
}
void Complex::display(){
cout<<fixed<<setprecision(2);
if(image > 0)
cout<<real <<"+"<<image<<"i"<<"\n";
else if(image < 0)
cout<<real<<image<<"i"<<"\n";
else
cout<<real;
}
Complex Complex::operator+(Complex &c2){
Complex temp;
temp.real = real + c2.real;
temp.image = image + c2.image;
return temp;
}
Complex Complex::operator-(Complex &c2){
Complex temp;
temp.real = real - c2.real;
temp.image = image - c2.image;
return temp;
}
Complex Complex::operator*(Complex &c2){
Complex temp;
temp.real = real * c2.real - image*c2.image;
temp.image = image*c2.real + real*c2.image;
return temp;
}
Complex Complex::operator/(Complex &c2){
Complex temp;
temp.real = (real * c2.real + image*c2.image) / (c2.real*c2.real + c2.image*c2.image);
temp.image = (image*c2.real - real*c2.image) / (c2.real*c2.real + c2.image*c2.image);
return temp;
}
Complex Complex::operator++(){
real++;
return *this;
}
Complex Complex::operator++(int){
Complex temp(*this);
++(*this);
return temp;
}
729

被折叠的 条评论
为什么被折叠?



