查万年历,2001年1月1日是星期1,然后计算偏移即可
#include<stdio.h> #include<stdlib.h> #include<string.h> bool IsLeapYear(int year){ return year%100!=0&&year%4==0||year%400==0; } int DaysInMonth(int year,int month){ switch(month){ case 1: return 31; case 2: return IsLeapYear(year)?29:28; case 3: return 31; case 4: return 30; case 5: return 31; case 6: return 30; case 7: return 31; case 8: return 31; case 9: return 30; case 10: return 31; case 11: return 30; case 12: return 31; default: return 0; } } int getDeltaInYears(int from,int to){ int current = from+1; int acc = 0; for(;current<to;current++){ acc += IsLeapYear(current)?366:365; } return acc; } int getDeltaInYear(int year,int monthFrom,int dateFrom,int monthTo,int dateTo){ if(monthFrom==monthTo) return dateTo-dateFrom; int acc = DaysInMonth(year,monthFrom)-dateFrom+1; int currentMonth = monthFrom+1; for(;currentMonth<monthTo;currentMonth++){ acc+= DaysInMonth(year,currentMonth); } acc += (dateTo-1); return acc; } char monthNameList[13][10] = { "None", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; int getMonthByName(char* monthName){//字符串比较用strcmp int month=1; for(;month<=12;month++){ if(strcmp(monthName,monthNameList[month])==0) break; //strcmp是==0时相等,容易记错 } return month; } char dayName[7][10]= { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; void Question2_7(){//习题2.7 上海交大 计算给定日期是周几 int date,month,year; char* monthName = (char*)malloc(sizeof(char*)); while(scanf("%d %s %d",&date,monthName,&year)!=EOF){//char*的输入输出不用& month = getMonthByName(monthName); int acc=0; if(year==2001){//2001.1.1是周一 acc = getDeltaInYear(2011,1,1,month,date); } else { if(year>2001){//工具函数是几道题通用的,那边自动+1了,这里要-1对齐 acc+= getDeltaInYears(2000,year); acc+= getDeltaInYear(year,1,1,month,date); } else { acc+= getDeltaInYear(year,month,date,12,31); acc+= 1; acc+= getDeltaInYears(year,2001); } } int mod = acc % 7; printf("%s\n",dayName[(mod+1)%7]); } } int main(){ Question2_7(); return 0; }