项目需要做一个日历,但前期平台准备工作还没有做好,就先将日历大致算法在控制台上写了一次。
/***************calendar.h****************/
#ifndef CALENDAR_H
#define CALENDAR_H
void printWeekday();
bool IsLeapYear(int year);
int getWeekday(int year,int month,int day);
int getDaysFormOneMonth(int month,int year);
void printMonthAndYear();
void printHead(int year,int month);
void printBody(int year,int month);
void printEnd(int year,int month);
void printDate(int weekday,int day);
#endif
/***************calendar.cpp****************/
// calendar.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "calendar.h"
#include <stdlib.h>
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int year=2011;
int month=9;
cout<<"输入年份 :";
cin>>year;
cout<<"输入月份 :";
cin>>month;
cout<<"生成日历如下 : "<<endl;
cout<<"**************************"<<endl;
cout<<year<<"年"<<month<<"月"<<endl;
cout<<"**************************"<<endl;
printWeekday();
printHead(year,month);
printBody(year,month);
printEnd(year,month);
system("pause");
return 0;
}
bool cheakInput(int year,int month)
{
return true;
}
void printWeekday()
{
char *pWeekday[]={"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
for(int i=0;i<7;i++)
printf("%s ",pWeekday[i]);
printf("/n");
}
void printDate(int weekday,int day)
{
/*for (int i=0;i<weekday;i++)
{
printf(" ");
}*/
if (day>0&&day<10)
{
printf(" ");
}
printf("%d ",day);
}
void printHead(int year,int month)
{
month--;
if (month<=0)
{
month=12;
year--;
}
int days_month=getDaysFormOneMonth(month,year);
if (days_month!=0)
{
int weekDay=getWeekday(year,month,days_month);
if (weekDay==6)
{
//有没有上个月的部分
return;
}
int day=days_month-weekDay;
for (int i=0;i<=weekDay;i++)
{
printDate(i,day++);
}
}
}
void printBody(int year,int month)
{
int days_month=getDaysFormOneMonth(month,year);
if (days_month!=0)
{
int weekDay=getWeekday(year,month,1);
for (int i=1;i<=days_month;i++)
{
if (weekDay==0)
{
cout<<endl;
}
printDate(weekDay,i);
if (++weekDay>6)
{
weekDay=0;
}
}
}
}
void printEnd(int year,int month)
{
month++;
if (month>12)
{
month=1;
year++;
}
int weekDay=getWeekday(year,month,1);
if (weekDay==0)
{
return;
}
int day=1;
for (int i=weekDay;i<=6;i++)
{
printDate(i,day++);
}
cout<<endl;
}
int getWeekday(int year,int month,int day)
{
//数组元素monthday[i]表示第i个月以前的总天数----
static int monthPassDay[] =
{
0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
};
int days = (year - 1) + monthPassDay[month - 1] + day;
days += (year - 1) /4 -(year - 1) /100 +(year - 1) /400 +((IsLeapYear(year) && month > 2) ? 1 : 0);
return days % 7;
}
// 判断是否是闰年
bool IsLeapYear(int year)
{
return (((year % 100 != 0) && (year % 4 == 0)) || (year % 400 == 0));
}
int getDaysFormOneMonth(int month,int year)
{
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 4:
case 6:
case 9:
case 11:
return 30;
case 2:
if(IsLeapYear(year))
return 29;
else
return 28;
default:
break;
}
return 0;
}