Date(类与对象)

题目描述

下面是一个日期类的定义,请在类外实现其所有的方法,并在主函数中生成对象测试之。

在这里插入图片描述

注意,在判断明天日期时,要加入跨月、跨年、闰年的判断 例如9.月30日的明天是10月1日,12月31日的明天是第二年的1月1日 2月28日的明天要区分是否闰年,闰年则是2月29日,非闰年则是3月1日

输入

测试数据的组数t 第一组测试数据的年 月 日 …
要求第一个日期的年月日初始化采用构造函数,第二个日期的年月日初始化采用setDate方法, 第三个日期又采用构造函数,第四个日期又采用setDate方法,以此类推。

输出

输出今天的日期
输出明天的日期

样例输入

4
2012 1 3
2012 2 28
2012 3 31
2012 4 30

样例输出

Today is 2012/01/03
Tomorrow is 2012/01/04
Today is 2012/02/28
Tomorrow is 2012/02/29
Today is 2012/03/31
Tomorrow is 2012/04/01
Today is 2012/04/30
Tomorrow is 2012/05/01

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

class Date
{
private:
	int year, month, day;

public:
	Date()
	{
		year = 1900;
		month = 1;
		day = 1;
	}

	Date(int y, int m, int d)
	{
		year = y;
		month = m;
		day = d;
	}

	void setDate(int y, int m, int d)
	{
		year = y;
		month = m;
		day = d;
	}

	int getYear() { return year; }
	int getMonth() { return month; }
	int getDay() { return day; }

	void print()
	{
		cout << year << "/" << setfill('0') << setw(2) << month << "/" << setfill('0') << setw(2) << day << endl;
	}

	/*
	//方法一:采用if-else语句判断可能出现的情况
	void addOneDay()
	{
		day++;
		//首先考虑对闰年和平年二月最后一天的处理
		if((year%4==0&&year%100!=0)||(year%400==0))		//若当前日期的年份为闰年
		{
			if(month==2&&day==30)						//对闰年2月30号的处理
			{
				day=1;
				month++;
			}
		}

		else if(month==2&&day==29)						//若当前日期的年份为平年,对2月29号的处理
		{
			day=1;
			month++;
		}

		//其次考虑对非2月的处理
		if(month==1||month==3||month==5||month==7||month==8||month==10||month==12)		//若当前月份为天数为31天的大月
		{
			if(day>31)
			{
				day-=31;
				month++;
			}
			if(month>12)			//若当前日期的月份为12月,则需考虑出现13月的情况
			{
				year++;
				month-=12;
			}
		}

		else if(month==4||month==6||month==9||month==11)								//若当前月份为天数为30天的小月
		{
			if(day>30)
			{
				day-=30;
				month++;
			}
		}
	}
	*/

	//方法二:采用数组保存每个月的天数,系统考虑问题
	bool isLeap(int year) { return year % 100 == 0 ? year % 400 == 0 : year % 4 == 0; } //闰年判断
	void addOneDay()
	{
		int monthDays[] = {0, 31, isLeap(year) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
		day++;
		if (day > monthDays[month]) //日期加一后天数超出该月份的最大天数
		{
			month++;
			day = 1;
		}
		if (month > 12) //月份数超出12时
		{
			year++;
			month = 1;
		}
	}
};

int main()
{
	int t, y, m, d;
	cin >> t;
	while (t--)
	{
		cin >> y >> m >> d;
		if (t % 2 == 1) //序号为奇数的日期采用构造函数初始化
		{
			Date today(y, m, d);
			cout << "Today is ";
			today.print();
			today.addOneDay();
			cout << "Tomorrow is ";
			today.print();
		}
		else //序号为偶数的日期采用setDate方法初始化
		{
			Date today;
			today.setDate(y, m, d);
			cout << "Today is ";
			today.print();
			today.addOneDay();
			cout << "Tomorrow is ";
			today.print();
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值