逆序输出函数模板

题目描述

编写一个逆序输出数据的函数模板reverse(复数的逆序是实部虚部置换)。

输入

第一行输入测试次数

每次测试输入一行,先输入一个大写字母表示数据类型, I表示整型、D表示双精度型、S表示string类型字符串、C表示复数类对象,最后输入数据。

输出

每次测试输出一行,逆序排列的数据

IO模式

本题IO模式为标准输入/输出(Standard IO),你需要从标准输入流中读入数据,并将答案输出至标准输出流中。

5
I 123456
D -235.172
S thisisatest
C -123 456
C 123 -456
 

654321
-271.532
tsetasisiht
456-123
-456+123

提示

可用类型转换函数将复数类对象转换为string.

模板函数内采用如下所示的方法可将数值型变量a转换成string型变量s:

#include "sstream"

......

ostringstream os;

string s;

os << a;

s = os.str();

#include<iostream>
#include<sstream>
using namespace std;

class Complex {
	int x, y;
public:
	Complex(int xx,int yy):x(xx),y(yy){}
	int getX() { return x; }
	int getY() { return y; }
	void setX(int xx) { x = xx; }
	void setY(int yy) { y = yy; }
	void print() {
		cout << x;
		if (y > 0) cout << '+';
		cout << y << endl;
	}
};

template<class T>
void reverse(T& data) {
	ostringstream os;
	string s;
	os << data;
	s = os.str();
	int n = s.length();
	int fullZero = 1;
	if (s[0] == '-') {
		cout << s[0];
		for (int i = n - 1; i > 0; i--) {
			if (s[i] == '0' && fullZero) continue;
			if (fullZero && s[i] != '0') fullZero = 0;
			cout << s[i];
		}
	}
	else {
		for (int i = n - 1; i >= 0; i--) {
			if (s[i] == '0' && fullZero) continue;
			if (fullZero && s[i]!='0') fullZero = 0;
			cout << s[i];
		}
			
	}
	cout << endl;
	
}

template<>
void reverse<Complex>(Complex & c) {
	int temp = c.getY();
	c.setY(c.getX());
	c.setX(temp);
	c.print();
}


int main() {
	int t;
	cin >> t;
	while (t--) {
		char type;
		cin >> type;
		if (type == 'I') {
			int n;
			cin >> n;
			reverse(n);
		}
		else if (type == 'D') {
			double n;
			cin >> n;
			reverse(n);
		}
		else if (type == 'S') {
			string n;
			cin >> n;
			reverse(n);
		}
		else if (type == 'C') {
			int x, y;
			cin >> x >> y;
			Complex com(x, y);
			reverse(com);

		}
	}
	//system("pause");
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值