思路:
1. 首先计算每月的第一天是星期几,据此推断第 b 个星期 c 是否在该月内,不在就输出 none。
2. 用基姆拉尔森计算公式判断第 y 年第 m 月第 d 天是星期几。用字符串流处理输出格式。
代码如下:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int caculateWeekDay(int y, int m, int d) //根据年月日判断星期几
{
if(m == 1 || m == 2)
{
m += 12;
y--;
}
int iWeek = (d+2*m+3*(m+1)/5+y+y/4-y/100+y/400)%7 + 1;
return iWeek;
}
bool isLeapYear(int &y) //判断是否是瑞年
{
return (y%400 == 0 || (y%4 == 0 && y%100 != 0));
}
string print(int y, int m, int d) //把年月日输出为题目要求格式
{
stringstream s1, s2, s3;
string ys, ms, ds, result;
s1 << y;
s1 >> ys;
s2 << m;
s2 >> ms;
s3 << d;
s3 >> ds;
if(m < 10) ms = "0"+ms;
if(d < 10) ds = "0"+ds;
result = ys + "/" + ms + "/" + ds + "\n";
return result;
}
int main()
{
int a, b, c, y1, y2;
int mon[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
cin >> a >> b >> c >> y1 >> y2;
for(int y = y1; y <= y2; y++)
{
mon[2] = isLeapYear(y) ? 29:28; //闰年2月29天
int week = caculateWeekDay(y, a, 1); //y年a月1号是星期 week
int goal; //目标日期
if(c < week)
goal = 1 + b*7 + c- week; //这个可以自己推一下
else
goal = 1 + (b-1)*7 +c - week;
if(goal > mon[a])
cout << "none\n";
else
cout << print(y, a, goal);
}
return 0;
}