C++有关日期些许题(2)
题目描述:
给出年分m和一年中的第n天,算出第n天是几月几号。
输入描述:
输入包括两个整数y(1<=y<=3000),n(1<=n<=366)。
输出描述:
可能有多组测试数据,对于每组数据,
按 yyyy-mm-dd的格式将输入中对应的日期打印出来。
示例
输入
2000 3
2000 31
2000 40
2000 60
2000 61
2001 60
输出
2000-01-03
2000-01-31
2000-02-09
2000-02-29
2000-03-01
2001-03-01
解题思路:
依旧用的是类进行问题解决。如果需要查看具体日期类的实现,可见笔者另一博客,链接为 日期类的实现 。
首先根据输入的年份判断是否是闰年,然后再根据该年每月的天数对输入的天数进行匹配计算,依次算出是哪月的哪天(调用对 ‘-=’ 的重载函数)。
示例程序:
#include<iostream>
using namespace std;
class Date
{
public:
Date(int year, int day)
{
//cout << getDays(year) << endl;
//判断日期是否有效
if (!(year <= 0 || day > getDays(year)))
{
//日期有效
_year = year;
m_d = day;
}
}
int getDays(int year);
int getDay(int year,int month);
Date& operator-=(int day)
{
if (_year <= 0 || day > getDays(_year))
{
//日期无效
_year = 0; _month = 0; _day = 0;
}
else
{
_day = day;
_month = 1;
while (_day > getDay(_year, _month))
{
_day -= getDay(_year, _month);
_month++;
}
}
return *this;
}
void display()
{
this->operator-=(this->m_d);
cout << _year << '-';
if (_month < 10)
cout << 0 << _month;
else
cout << _month;
if (_day < 10)
cout << '-' << 0 << _day << endl;
else
cout << '-' << _day << endl;
}
private:
int _year;
int _month;
int _day;
int m_d;//中间变量
};
static int days[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int Date::getDays(int year)
{
int num = 0;
for (int i = 1; i <= 13; i++)
{
num += days[i];
}
if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
{
num += 1;
}
return num;
}
int Date::getDay(int year, int month)
{
static int days[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
int day = days[month];
if (month == 2 && (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)))
{
day += 1;
}
return day;
}
void test()
{
int i, j;//i为年份,j为天数
while (cin >> i >> j)
{
if((1 <= i && i <= 3000)&&(1 <= j && j <= 366))
{
Date d(i, j);
d.display();
i = 0; j = 0;
}
}
}
int main()
{
test();
system("pause");
return 0;
}
运行结果:
此题为牛客网上一例题,见下附链接:
打印日期