Date.h文件如下:
//打印万年历从1900年起 #ifndef DATE_H #define DATE_H #include <string.h> #define OUT_OF_YEAR -1 //是否是闰年 bool isLeap(int year){ if(year<1900) return OUT_OF_YEAR; return (year%4==0)&&(year%100!=0)||(year%400==0); } //从year到1900年间闰年个数 int LeapYearNum(int year){ if(year<1900) return OUT_OF_YEAR; int LeapYear=0; for (int i=1900;i<=year;i++) { if(isLeap(i)){ ++LeapYear; } } return LeapYear; } //到year开始到1900年的天数 int GetDayNum(int year){ if(year<1900) return OUT_OF_YEAR; return LeapYearNum(year)+(year-1900)*365; } //year年,mounth月的天数 int GetDayOfMouth(int year,int mounth){ if (year<1900 || mounth<1||mounth>12) return OUT_OF_YEAR; int dayNum=0; switch (mounth) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: dayNum=31; break; case 4: case 6: case 9: case 11: dayNum=30; break; case 2: if(isLeap(year)){ dayNum=29; }else{ dayNum=28; } break; default: dayNum=0; } return dayNum; } //到1900年的天数 int getDay(int year,int mouth){ int mouthDay=0; for (int i=1;i<mouth;i++) { mouthDay+=GetDayOfMouth(year,i); } return GetDayNum(year)+mouthDay; } int getWeek(int year,int mouth){ return getDay(year,mouth)%7+1; } //得到星期英文缩写 char* getWeekChar(int i){ if (i<1||i>7) return ""; char *WeekChar=" "; switch(i){ case 1: WeekChar="Mon"; break; case 2: WeekChar="Tue"; break; case 3: WeekChar="Wed"; break; case 4: WeekChar="Thu"; break; case 5: WeekChar="Fri"; break; case 6: WeekChar="Sat"; break; case 7: WeekChar="Sun"; break; default: WeekChar=""; } return WeekChar; } //打印月份 void printMouth(int year,int mouth){ int startWeek=getWeek(year,mouth); int days=GetDayOfMouth(year,mouth); printf("*********************%d年%d月****************************** ",year,mouth); int dayIndex=1; printf(" "); for (int i=1;i<=7;i++) { printf(" %s ",getWeekChar(i)); } printf(" "); for (int i=1;i<=50;i++) { if (dayIndex>days) break; if (i<startWeek) { printf(" "); }else{ printf("%4d ",dayIndex); dayIndex++; } if (i%7==0) printf(" "); } printf(" "); } #endif
#include <stdio.h> #include "Date.h" int main( void ) { printMouth(2013,10); }
运行结果如下:
*********************2013年10月****************************** Mon Tue Wed Thu Fri Sat Sun 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 请按任意键继续. . .