九度题目1043:Day of Week

来源:互联网 发布:go并发编程实战 pdf 编辑:程序博客网 时间:2024/04/27 16:43

原题链接:http://ac.jobdu.com/problem.php?pid=1043

题目描述:
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


这题其实可以仿照上一题的日期差值,算出输入的日期距离1年1月1日有多少天,然后模7

幸运的是我知道有个公式可以直接根据年月日算出星期,但是公式记不住,后来上网搜了搜,发现网友的http://www.360doc.com/content/10/0517/14/11192_28043397.shtml这篇文章写的通俗易通,推理也没那么难,一下就记住了,还可以自己推,公式就是

(year-1+(year-1)/4-(year-1)/100+(year-1)/400+d)%7

其中year表示输入的年份,d表示当前年份距离当前年的1月1号有多少天,如2014年1月1号,那么year=2014,d=1


代码如下

#include <stdio.h>#include <stdlib.h>#include <string.h>#define LEN 10int mon[12]={31,28,31,30,31,30,31,31,30,31,30,31};char months[12][9]={"January","February","March","April","May","June","July","August","September","October","November","December"};int pos(char *month){int i;for (i=0;i<12;i++){if (!strcmp(months[i],month)){return i;}}return -1;}int isLeapYear(int year){if((year%4==0&&year%100!=0)||year%400==0){return 1;}return 0;}int days(int year,int month,int day){int i,sum=0;for (i=0;i<month;i++){sum+=mon[i];}if(isLeapYear(year)&&month>2){return sum+1+day;}return sum+day;}void display(int week){switch (week){case 1:printf("Monday\n");break;case 2:printf("Tuesday\n");break;case 3:printf("Wednesday\n");break;case 4:printf("Thursday\n");break;case 5:printf("Friday\n");break;case 6:printf("Saturday\n");break;case 0:printf("Sunday\n");break;}}int main(){int day,year;char month[LEN];while(scanf("%d%s%d",&day,month,&year)==3){int m=pos(month);int d=days(year,m,day);int week=(year-1+(year-1)/4-(year-1)/100+(year-1)/400+d)%7;display(week);}return 0;}


如果文章有什么错误或者有什么建议,欢迎提出,大家共同交流,一起进步

文章转载请注明出处,请尊重知识产权

0 0
原创粉丝点击