思路:从公元元年(即1年1月1日)到给定日期的天数
代码如下:
#include
#include
using namespace std;
class Date //创建一个日期Date类
{
private: //数据成员
int year;
int month;
int day;
public: //成员函数
Date(); //构造函数
void setDate(); //输入日期
void isLeapYear(); //判断是否为闰年
int getSkip(Date date); //计算从公元元年(即1年1月1日)到给定日期的天数
void month1(int i, int &count); //闰年的12个月的天数
void month2(int i, int &count); //非闰年的12个月的天数
};
Date::Date() //构造函数的定义
{
year = 0;
month = 0;
day = 0;
}
void Date::setDate() //输入日期的函数定义
{
cin >> year;
cin >> month;
cin >> day;
}
void Date::isLeapYear() //判断是否为闰年的函数定义
{
if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0)
cout << year << " is leap year." << endl;
else cout << year << " is not leap year." << endl;
}
void Date::month1(int i, int &count) //闰年的12个月的天数的函数定义
{
switch (i)
{
case 1:count += 31; break;
case 2:count += 29; break;
case 3:count += 31; break;
case 4:count += 30; break;
case 5:count += 31; break;
case 6:count += 30; break;
case 7:count += 31; break;
case 8:count += 31; break;
case 9:count += 30; break;
case 10:count += 31; break;
case 11:count += 30; break;
case 12:count += 31; break;
}
}
void Date::month2(int i, int &count) //非闰年的12个月的天数的函数定义
{
switch (i)
{
case 1:count += 31; break;
case 2:count += 28; break;
case 3:count += 31; break;
case 4:count += 30; break;
case 5:count += 31; break;
case 6:count += 30; break;
case 7:count += 31; break;
case 8:count += 31; break;
case 9:count += 30; break;
case 10:count += 31; break;
case 11:count += 30; break;
case 12:count += 31; break;
}
}
int Date::getSkip(Date date) //计算从公元元年(即1年1月1日)到给定日期的天数的函数定义
{
int year = date.year, month = date.month, day = date.day;
int count = 0; //count用来表示该日期到公元元年的天数差
for (int i = 1; i < year; i++)
{
if ((i % 4 == 0 && i % 100 != 0) || (i % 400 == 0))
{
count += 366;
}
else
{
count += 365;
}
}
for (int i = 1; i < month; i++)
{
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
{
month1(i, count);
}
else
{
month2(i, count);
}
}
count += day;
return count;
}
int main()
{
int date1_day = 0, date2_day = 0; //date1_day和 date2_day用来存储从从公元元年(即1年1月1日)到给定日期的天数
Date date1; //创建date1类
date1.setDate(); //输入类date1的日期
Date date2; //创建date2类
date2.setDate(); //输入类date2的日期
date1.isLeapYear(); //判断date1的日期是否是闰年
date2.isLeapYear(); //判断date2的日期是否是闰年
date1_day = date1.getSkip(date1);
date2_day = date2.getSkip(date2);
cout << "The skip of two date is " << abs(date1_day - date2_day) << endl;
return 0;
}