> 文章列表 > 【id:32】【20分】B. Date(类与构造)

【id:32】【20分】B. Date(类与构造)

【id:32】【20分】B. Date(类与构造)

题目描述

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

 

注意,在判断明天日期时,要加入跨月、跨年、闰年的判断

例如9.月30日的明天是10月1日,12月31日的明天是第二年的1月1日

2月28日的明天要区分是否闰年,闰年则是2月29日,非闰年则是3月1日

输入

测试数据的组数t

第一组测试数据的年 月 日

..........

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

输出

输出今天的日期

输出明天的日期


输入样例1 

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


输出样例1

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


C++中设置填充字符的代码参考如下:

cout << setfill('0') << setw(2) << month; //设置宽度为2,前面补'0'

需要头文件#include <iomanip>

 

 

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;class Date
{int year, month, day;
public://初始年月日Date();Date(int y, int m, int d);void print();void addOneDay();
};//初始年月日
Date::Date()
{year = 1900;month = 1;day = 1;
}
Date::Date(int y, int m, int d)
{year = y;month = m;day = d;
}//明天
void Date::addOneDay()  //明天日期判断
{int dmax = 0;   //设置局部变量,用于与增一天后日期作比较day++;if (month == 2)  //先判断是否为2月{if (year % 4 == 0 && year / 100 != 0 || year % 400 == 0)  //闰年判断{dmax = 29;}else{dmax = 28;}}else if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)  //大月判断{dmax = 31;}else   //小月判断{dmax = 30;}if (day > dmax)  //跨月份判断{day = day - dmax;month++;}if (month > 12)  //跨年判断{month = month - 12;year++;}
}//  打印2012/01/03
void Date::print()
{//cout << setfill('0') << setw(2) << month; //设置宽度为2,前面补'0'cout << year << "/" << setfill('0') << setw(2) << month << "/" << setfill('0') << setw(2) << day << endl;
}int main()
{int t;cin >> t;while (t--){int a, b, c;cin >> a >> b >> c;//初始日期Date A(a, b, c);//打印日期cout << "Today is ";A.print();//判断明天日期A.addOneDay();//打印明天日期cout << "Tomorrow is ";A.print();}
}