例2.4 Day of Week(九度教程第7题)
题目
时间限制: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.今天和所给定的那天相隔几天。利用其对7求余数便可以知道所给定的那天是星期几。
预处理部分和例2.3保持一致。
改隶中的解法旨在展示一种处理日期类问题的基本思路和一般方法,即利用天数间隔来解决日期类问题,同时也提出了处理区间问题的一种重要方法—预处理。
注意:
1,使用3元表达式时,不要忘记?
2, %s、%d、%c、%f 等来输出或读取:字符串、整数、字符或浮点数
3, printf("%s",weekName[(days%7+7)%7]);
puts(weekName[(days%7+7)%7]); //和上面一行效果一样
gets() & puts() 函数
char *gets(char *s) 函数从 stdin 读取一行到 s 所指向的缓冲区,直到一个终止符或 EOF。
int puts(const char *s) 函数把字符串 s 和一个尾随的换行符写入到 stdout。
4,用char[][]二维数组来存一组字符串的用法
char weekName[7][20]={//周名,每个周名对应下标0-6
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
代码:
#include<stdio.h>
#include<string.h> //strcmp的头文件
//定义宏判断是否为闰年,方便计算每月天数
#define LeapYear(x) x%400==0 || (x%4==0 && x%100!=0) ?1:0 //不要忘记带?号
int dayOfMonth[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
};
struct Date{//日期类,方便日期的推移
int day;
int month;
int year;
void nextDay(){//计算下一天的日期
day++;
if(day>dayOfMonth[month][LeapYear(year)])
{
day=1;
month++;//进入下一月
if(month>12){
month=1;
year++;//进入下一年
}
}
}
};
int buf[3001][13][32];//保存预处理的天数
char monthName[13][20]={//月名,每个月名对应下标1-12
"",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
};
char weekName[7][20]={//周名,每个周名对应下标0-6
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
int main()
{
Date tmp;
int cnt=0; //天数计数
tmp.year=0;
tmp.month=1;
tmp.day=1; // 初始化日期类对象为0年1月1日
while(tmp.year!=3001){ //预处理出每一天与原点日期的天数差
buf[tmp.year][tmp.month][tmp.day]=cnt; //将该日与0年1月1日的天数差保存起来
tmp.nextDay(); //计算下一天日期
cnt++; //计数器累加,代表与原点日期又增加一天
}
int d,m,y;
char s[20];
while(scanf("%d%s%d",&d,s,&y)!=EOF){
for(m=1;m<=12;m++)
{
if(strcmp(s,monthName[m])==0){
break; //将输入字符串与月名比较得出月数
}
}
//计算给定日期与今日日期的天数间隔(注意可能为负)
int days=buf[y][m][d]-buf[2012][7][16];
//今天(2012.7.16)为星期一,对应数组下标为1,则计算经过days天后的下标
days+=1;
//将计算后得出的下标用7对其取模,并且保证其为非负数,则该下标即为答案所对应的下标,输出即可
printf("%s\n",weekName[(days%7+7)%7]);
//puts(weekName[(days%7+7)%7]);
}
}