法1:通过蔡勒公式计算星期数

#include <iostream> 
using namespace std;

int Judge(int n)
{
	if((n%4==0&&n%100!=0)||(n%400==0))return 1;
	else return 0; 
}

int Whatdayisittoday(int yyyy,int mm,int dd)
{
		//string res[7]={"日","一","二","三","四","五","六"};
		//w对7取模得:0-星期日,1-星期一,2-星期二,3-星期三,4-星期四,5-星期五,6-星期六 
		int w,r;
		int c,y,m,d;
		c=(int)yyyy/100;//世纪数-1 
		y=yyyy-c*100;//本世纪第n年 
		if(mm<=2)//某年的1、2月要看作上一年的13、14月来计算 
		{
			y=y-1;
			m=mm+12;
		}
		else m=mm;
		d=dd;
		w=(int)(c/4)-2*c+y+(int)(y/4)+(int)(13*(m+1)/5)+d-1;//蔡勒公式 
		while(w<0)w=w+7;//不能用负数求模,可以加它的循环,这是等价的,一直加到变成正数为止 
		r=w%7;
		return r; 
}

void CalendarPrint(int y,int m)
{
	string res[7]={"一","二","三","四","五","六","日"};
	int days[13]={29,31,28,31,30,31,30,31,31,30,31,30,31};
	for(int i=0;i<7;i++)cout<<res[i]<<" ";
	cout<<endl;
	int blanket;
	if(Whatdayisittoday(y,m,1)==0)blanket=6;
	else blanket=Whatdayisittoday(y,m,1)-1;
	for(int i=blanket;i>0;i--)cout<<"   ";
	
	for(int i=1;i<=days[m];i++)
	{
		if(i<10)cout<<" "<<i<<" ";
		else cout<<i<<" ";
		if(Whatdayisittoday(y,m,i)==0)cout<<endl;
	}
	if(m==2&Judge(y)==1)cout<<29;
	cout<<endl;
};

int main()
{
	while(1)
	{
		int y,m;
		cout<<"---------------------------------"<<endl;
		cout<<"日历打印\n请输入要打印的年、月:"; 
		cin>>y>>m;
		CalendarPrint(y,m); 
	}
	
 } 

法2:以1900年1月1日 星期一 为参考

#include <iostream> 
using namespace std;

int Judge(int n)
{
	if((n%4==0&&n%100!=0)||(n%400==0))return 1;
	else return 0; 
}

int DaysCount(int yyyy,int mm,int dd)
{
	int day[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};int days=0;
	if(Judge(yyyy)==1)
	{
		for(int i=1;i<mm;i++)
		{
			if(i==2)days++;//29
			days=days+day[i];
		}
	}
	else
	{
		for(int i=1;i<mm;i++)
		{
			days=days+day[i];
		}
	}
	days=days+dd;
	//cout<<"是该年的第"<<days<<"天"<<endl;;
	return days;
}

int Whatdayisittoday(int yyyy,int mm,int dd)
{
		//1900年1月1日星期一 yyyy年mm月dd日星期几?
		int years=yyyy-1900;int leapdays=0,days=0;
		for(int i=1900;i<yyyy;i++)
			if(Judge(i)==1)leapdays++;
		days=years*365+leapdays+DaysCount(yyyy,mm,dd);
		int r=days%7;
		//cout<<days<<" "<<leapdays<<" "<<r<<" "<<years<<endl; 
		return r; 
}

void CalendarPrint(int y,int m)
{
	//string res[7]={"日","一","二","三","四","五","六"};
	string res[7]={"一","二","三","四","五","六","日"};
	int days[13]={29,31,28,31,30,31,30,31,31,30,31,30,31};
	for(int i=0;i<7;i++)cout<<res[i]<<" ";
	cout<<endl;
	int blanket;
	if(Whatdayisittoday(y,m,1)==0)blanket=6;
	else blanket=Whatdayisittoday(y,m,1)-1;
	for(int i=blanket;i>0;i--)cout<<"   ";
	
	for(int i=1;i<=days[m];i++)
	{
		if(i<10)cout<<" "<<i<<" ";
		else cout<<i<<" ";
		if(Whatdayisittoday(y,m,i)==0)cout<<endl;
	}
	if(m==2&Judge(y)==1)cout<<29;
	cout<<endl;
};

int main()
{
	while(1)
	{
		int y,m;
		cout<<"---------------------------------"<<endl;
		cout<<"日历打印\n请输入要打印的年、月:"; 
		cin>>y>>m;
		CalendarPrint(y,m); 
	}
	
 } 

输出

posted on 2020-02-27 01:50  海月CSDN  阅读(101)  评论(0编辑  收藏  举报