PTA 7-2 复数与基本类型的加减运算

定义复数类Complex,并重载运算符:+、-,实现一个整数与复数类对象的加减运算。定义成员函数print,调用该函数时,以格式“(real,imag)”输出当前对象的实部和虚部,例如:对象的实部和虚部分别是4.2和6.5,则调用print函数输出格式为:(4.2,6.5)。主函数已给出,根据提示完成程序设计。

int main()
{
double r, m;
cin >> r >> m;
Complex c(r, m);
int n;
cin>>n;
Complex c1;
c1 = n+c;
Complex c2=c-n;
Complex c3=n-c;
c1.print();
c2.print();
c3.print();
return 0;
}

输入格式:
输入有两行,第1行为复数的实部与虚部 第2行为整数n

输出格式:
共3行输出,第1行为n+c1的结果,第2行为c1-n的结果,第3行为n-c1的结果。。

输入样例:
在这里给出一组输入。例如:

4.2 6.5
2

输出样例:
在这里给出相应的输出。例如:

(6.2,6.5)
(2.2,6.5)
(-2.2,-6.5)

#include<iostream>
using namespace std;
class Complex
{
public:
	Complex(double r = 0, double i = 0) :real(r), imag(i)
	{
	}
	friend Complex operator+(double n, Complex p);
	
	friend Complex operator-( double  n, Complex o);
	friend Complex operator-(Complex o,double  n);
	void print() const;
private:
	double real;
	double imag;
};
Complex operator+(double n, Complex p) {
	Complex c;
	c.real = p.real + n;
	c.imag = p.imag;
	return c;
}
Complex operator-(Complex o, double  n) {
	Complex c;
	c.real = o.real - n;
	c.imag = o.imag ;
	return c;
}
 Complex operator-(double  n, Complex o) {
	 Complex c;
	 c.real =  n-o.real ;
	 c.imag = 0-o.imag;
	 return c;
}
void Complex::print() const
{
	cout << "(" << real << "," << imag << ")" << endl;
}
int main()
{
	double r, m;
	cin >> r >> m;
	Complex c(r, m);
	int n;
	cin >> n;
	Complex c1;
	c1 = n + c;
	Complex c2 = c - n;
	Complex c3 = n - c;
	c1.print();
	c2.print();
	c3.print();
	return 0;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值