实验十四 运算符重载3 (类型转换 四进制加法)

A. 日期比较(运算符重载之类型转换)

定义一个日期类CDate,包含属性:年、月、日,都是整数。

构造函数含单个参数,参数是八位整数,默认值为0,实现整数转为日期类型,例如参数为20170612,转为year = 2017, month = 6, day = 12

实现转换运算符重载,把日期类型转为整数,例如2017年6月8日转为20170608。注意,如果月或日小于10,转化为整数时要补0

实现日期的输出函数print,具体格式看示范数据

主函数如下,不能修改,请实现上面的日期类

int main()
{
	int t, t1, t2;
	CDate c1, c2;
	cin >> t;
	while (t--)
	{
		cin >> t1 >> t2;
		c1 = t1;
		c2 = t2;
		((c1 > c2) ? c1 : c2).print(); //日期大的输出,在代码c1 > c2中,会自动把c1和c2转换为整数进行比较
	}
	return 0;
}

输入

第一行输入t表示有t对日期

接着每两行输入两个日期

输入t对

输出

每行输出一对日期中,日期大的信息

输入样例1 

2
20170625
20160528
19981111
20021212
输出样例1

2017年06月25日
2002年12月12日

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

class CDate
{
private:
	int year, month, day;
public:
	CDate()
	{

	}
	CDate(int r)
	{
		year = r / 10000; month = r / 100 % 100; day = r % 100;

	}
	operator int()   //把整形赋值给类类型
	{
		int num = year * 10000 + month * 100 + day;
		return num;
	}
	void print()
	{
		cout << year << "年" << setw(2) << setfill('0') << month << "月" << setw(2) << setfill('0') << day << "日" << endl;
	}

};

int main()
{
	int t, t1, t2;
	CDate c1, c2;
	cin >> t;
	while (t--)
	{
		cin >> t1 >> t2;
		c1 = t1; //把整形变量赋值给类类型
		c2 = t2;
		((c1 > c2) ? c1 : c2).print(); //日期大的输出,在代码c1 > c2中,会自动把c1和c2转换为整数进行比较
	}
	return 0;
}

 四进制加法(运算符重载)

题目描述

定义一个四进制的类,重定义“+”号实现四进制数的累加。

输入

第一行输入所需要的四进制数的个数

第二行开始,依次输入四进制数

输出

所有输入四进制数累加的和

输入样例1

3
13
2
21

输出样例1

102

#include<iostream>
using namespace std;
class four
{
private:
	int a;
public:
	four()
	{
		a = 0;
	}
	four(int aa) :a(aa)
	{

	}
	int geta()
	{
		return a;
	}
	four operator +(four f)
	{
		int sum = 0; int count = 0; int up = 0;
		int x = a; int y = f.a;
		while (x || y || up)//当三个都为0停止循环
		{
			int add = x % 10 + y % 10 + up; //个位数判断是否进位  下一次循环add是十位数判断是否进位
			int temp = add % 4;//确认个位数   下一次循环确认十位数
			sum += temp * pow(10, count); //个位数为temp*10的0次方 十位数为temp*10的1次方 以此类推
			if (add >= 4)
				up = 1;
			else
				up = 0;
			x = x / 10; //十位数 百位数 千位数  循环直至无法进位
			y = y / 10;//十位数  百位数 千位数 
			count++;
		}
		four temp(sum);
		return temp;
	}
};
int main()
{
	four sum;
	int t, x;
	cin >> t;
	while (t--)
	{
		cin >> x;
		four f(x);
		sum = sum + f;
	}
	cout << sum.geta();
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值