您的位置:首页 > 其它

[日期类问题] 例 2.4 Day of week(九度教程第 7 题)

2016-11-21 22:34 309 查看

题目

时间限制:1 秒 内存限制:32 兆 特殊判题:否

题目描述:

We now use the Gregorian style of dating in Russia. The leap years are years with number divisible by 4 but not divisible by 100, or divisible by 400.

For example, years 2004, 2180 and 2400 are leap. Years 2004, 2181 and 2300 are not

leap.

Your task is to write a program which will compute the day of week corresponding to a given date in the nearest past or in the future using today’s agreement about dating.

输入:

There is one single line contains the day number d, month name M and year

number y(1000≤y≤3000). The month name is the corresponding English name

starting from the capital letter.

输出:

Output a single line with the English name of the day of week corresponding to

the date, starting from the capital letter. All other letters must be in lower case.

样例输入:

9 October 2001

14 October 2001

样例输出:

Tuesday

Sunday

来源:

2008 年上海交通大学计算机研究生机试真题

分析

在上题的基础上,只需要改进如下:

1. 知道今天是星期几

2. 计算日期与今天的差值

3. 求出日期是星期几

代码

#include<iostream>
#include<string.h>
#define ISLEAPYEAR(x) x % 100 != 0 && x % 4 == 0 || x % 400 == 0 ? 1 : 0 //简洁写法
using namespace std;

int daysOfMonth[13][2] =
{
0, 0,
31, 31,
28,29,
31,31,
30,30,
31,31,
30,30,
31,31,
31,31,
30,30,
31,31,
30,30,
31,31
};

char monthName[13][20] =
{
"",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
}; //月名 每个月名对应下标1到12

char weekName[8][20] =
{
"",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday",
}; //周名 每个周名对应下标1到7

class Date //注意不要加括号
{
public:
int year;
int month;
int day;
Date() //初始化日期为0/1/1 作为基准
{
year = 0;
month = 1;
day = 1;
}
void update() //将日期加一天
{
day++;
if(day > daysOfMonth[month][ISLEAPYEAR(year)])
{
day = 1;
month ++;
if(month > 12)
{
month = 1;
year ++;
}
}
}
};

int Abs(int x)
{
return (x >= 0 ? x : -1*x);
}

int buf[6001][13][32]; //用来存储每个日期与基准日期的差值

int main()
{
Date temp;
int count = 0;
while(temp.year < 6000)
{
buf[temp.year][temp.month][temp.day] = count;
temp.update();
count ++;
}
int d, m, y;
char s[20];

while(cin >> d >> s >> y) //此处注意对于格式的控制
{
for(m = 1; m <= 12; m ++)
if(strcmp(s, monthName[m]) == 0) break;
int gap = buf[y][m][d] - buf[2016][11][21];
if(gap >= 0)
cout << weekName[(gap % 7 + 1)] << endl;
else
cout << weekName[(gap % 7 + 7 + 1)] << endl;
}
return 0;
}


总结

day > daysOfMonth[month][ISLEAPYEAR(year)] 取数组元素的时候不要和函数混了

注意此题中数组的使用,很方便,另外数组的序号也很讲究
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: