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
    评论
为实现复数类的++ --运算,我们需要对复数类进行运算符重载。我们可以重载前置++和--运算符和后置++和--运算符。 下面是一个简单的复数类的定义: ```cpp class Complex { private: double real_; double imag_; public: Complex(double real = 0, double imag = 0) : real_(real), imag_(imag) {} double real() const { return real_; } double imag() const { return imag_; } Complex operator++(); //前置++ Complex operator--(); //前置-- Complex operator++(int); //后置++ Complex operator--(int); //后置-- }; Complex Complex::operator++() { real_++; imag_++; return *this; } Complex Complex::operator--() { real_--; imag_--; return *this; } Complex Complex::operator++(int) { Complex temp(*this); real_++; imag_++; return temp; } Complex Complex::operator--(int) { Complex temp(*this); real_--; imag_--; return temp; } ``` 前置++和--运算符直接将实部和虚部分别加/减1即可。 后置++和--运算符需要先保存当前对象的值,然后再将实部和虚部分别加/减1,最后返回保存的对象值。 下面是一个使用复数类的示例: ```cpp int main() { Complex a(1, 2); Complex b = ++a; Complex c = b--; cout << "a=" << a.real() << "+" << a.imag() << "i" << endl; cout << "b=" << b.real() << "+" << b.imag() << "i" << endl; cout << "c=" << c.real() << "+" << c.imag() << "i" << endl; return 0; } ``` 输出结果为: ``` a=2+3i b=2+3i c=3+4i ``` 可以看到,前置++和后置--运算符都可以正常工作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值