问题描述
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.
输入样例
21 December 2012
5 January 2013
输出样例
Friday
Saturday
思路
- 用y表示输入的年份,m表示输入的单词对应的月份,d表示输入的是几号
- 利用2021年1月1日是星期五作为推算的依据,先从年份入手,逐年推算出1月1日是星期几直到推算出y年1月1日是星期几为止
- 接下来,利用y年每个月的天数累加得到y年m月1日与y年1月1日相差的天数,再加上y年m月d日与y年m月1日相差的天数得到相差总天数day
- 最后根据y年1月1日是星期几及相差天数day即可推算出所求日期是星期几
C语言代码
#include<stdio.h>
#include<string.h>
const int month[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}
}; //平年、闰年每个月的天数,二维 0 表示平年,1 表示闰年
const char monthName[13][10] = { {'\0'} , {"January"} , {"February"} , {"March"} , {"April"} ,
{"May"} , {"June"} , {"July"} , {"August"} ,
{"September"} , {"October"} , {"November"} , {"December"}
}; //每个单词代表的月份
const char week[7][10] = { {"Sunday"} , {"Monday"} , {"Tuesday"} , {"Wednesday"} ,
{"Thursday"} , {"Friday"} , {"Saturday"}
}; //每个单词代表的星期,0 表示星期天,1 表示星期一,依此类推
const int standard_y = 2021; //推算的标准年份,2021年
const int standard_m = 1; //推算的标准月份,1月
const int standard_d = 1; //推算的标准日期,1号
const int standard_w = 5; //2021年1月1日是星期五
//判断是否是闰年
bool isleap(int year){
return (year%4==0 && year%100!=0) || (year%400==0);
}
//通过与monthName比较行字符串,返回对应的月份
int getMonth(char str[]){
for(int i = 0; i < 13; i++)
if(!strcmp(str,monthName[i]))
return i;
}
int main(){
int d, m, y;
char E_m[10];
while(scanf("%d%s%d", &d, E_m, &y) != EOF){ //循环输入样例直到文件末尾
m = getMonth(E_m);
int temp_y = standard_y;
int temp_m = standard_m;
int temp_w = standard_w;
int temp_d = standard_d;
while( y < temp_y){ //当样例年份小于2021时,推算出y年1月1日是星期几
temp_y--;
if(isleap(temp_y)){ //若是闰年,366天,366%7=2,星期数往前推2天
temp_w -= 2;
if(temp_w < 0) //出现负数时,用7校正得到正确的星期数
temp_w += 7;
}
else{ //若是平年,365天,365%7=1,同理每次星期数往前推1天
temp_w -= 1;
if(temp_w < 0)
temp_w +=7;
}
}
while( y > temp_y){ //若样例年份大于2021,推算出y年1月1日是星期几
if(isleap(temp_y))
temp_w = (temp_w + 2) % 7;
else
temp_w = (temp_w + 1) % 7;
temp_y++;
}
int day = 0;
while(temp_m < m){ //推算出 y年1月1日与y年m月1日相差几天
day += month[temp_m][isleap(y)];
temp_m++;
}
day += d - temp_d; //计算出y年1月1日与y年m月d日相差总天数
temp_w = (temp_w + day%7) % 7; //得到最后的星期数
printf("%s\n", week[temp_w]);
}
return 0;
}