复数(输入输出运算符重载)

题目描述

定义一个复数类,通过重载运算符:>>和<<,实现复数的输入输出。

主函数定义如下:

int main()

{

int n;

double r, i;

CComplex x;

cin >> n;

while (n–) {

cin >> x;

cout << x;

}

return 0;

}

输入

首先创建一个复数,实部和虚部均为0。

输入测试次数t

随后每个测试,调用运算符>>,接受两个数值,分别为要修改的Complex对象的实部和虚部。

输出

每次更改实部和虚部,调用运算符<<,输出复数类。注意考虑实部为零、虚部为负数和零等特殊情况。

输入样例

5
1 2
1 -2
0 0
0 -2
-2 0

输出样例

1+2i
1-2i
0
-2i
-2

代码

#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
class CComplex{
	private:
		int real,image;
	public:
		CComplex(){real=0;image=0;}
		CComplex(int x,int y):real(x),image(y){}
		friend istream& operator>>(istream& is,CComplex& t); 
		friend ostream& operator<<(ostream& os, CComplex& t);
		void set(int x, int y){
			real=x;
			image=y;
		}
		void get(int &x, int &y){
			x=real;
			y=image;
		}
		int getreal(){return real;}
		int getimage(){return image;}
};
istream& operator>>(istream& is,CComplex& t){
	int x,y,x1,y1;
	char c1,c2;
	x=0;
	y=0;
	is>>x1>>y1;
	x=x1;
	y=y1;
	t.set(x,y);
	return is;
}
ostream& operator<<(ostream& os, CComplex& t)
{
 	int x, y;
 	t.get(x, y);
 	if(x!=0&&y!=0)
 	os  << x;
 	if (y > 0)
 	{
 		os << '+';
 		os  << y<<'i'<<endl;
    }
 	else if (y <0)
 	{ 
 		os  << y<<'i'<<endl;
 	}
 	else
	{
 		os  << x<<endl;	
	}
   return os;
}
int main()
{
	int n;
	double r, i;
	CComplex x;
	cin >> n;
	while (n--) 
	{
		cin >> x;
		cout << x;
	}
	return 0;
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值