Posted on 2006-05-13 16:23
SmallTalk 阅读(662)
评论(1) 编辑 收藏 引用 所属分类:
C++小程序
//calendar.cpp----打印某年年历
#include <iostream.h>
#include <iomanip.h>
int year;
int weekday;
//---------------------------------------
void PrintMonth(int m);//打印每个月
void PrintHead(int m);//打印月标题
int DaysOfMonth(int m);//计算每个月天数
bool IsLeapYear(int m);//闰年判断
long WeekdayOfYear(int y);//某年的第一天
//---------------------------------------
int main()
{
//打印年历头
cout << "please enter the year:";
cin >> year;
if (year<1)
cout << "输入的年不能小于1!"<<endl;
cout <<"============================="<<endl;
cout << " "<<year<<"年 "<<endl;
cout <<"============================="<<endl;
//求开头第一天星期几
weekday=WeekdayOfYear(year);
//打印每个月
for (int i=1;i<=12;i++)
PrintMonth(i);
return (0);
}
//-----------------------------------------
void PrintMonth(int m)
{
//打印月标题
PrintHead(m);
//计算每个月天数
int days=DaysOfMonth(m);
//打印日期
for (int i=1;i<=days;i++)
{
cout << setw(5)<<i;
weekday=(weekday+1)%7;
if (weekday%7==0)
{
cout << endl;
cout << " ";
}
}
cout <<endl;
}
//-------------------------------------------
void PrintHead(int m)
{
cout << setw(3)<<m<<"月"<<" 日 一 二 三 四 五 六"<<endl;
cout <<" ";
for (int i=0;i<weekday;i++)
cout << " ";
}
//--------------------------------------------
int DaysOfMonth(int m)
{
switch (m)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12: return(31);break;
case 4:
case 6:
case 9:
case 11: return(30);break;
default:
if(IsLeapYear(year))
return(29);
else
return(28);
}
}
//---------------------------------------------
bool IsLeapYear(int y)
{
return (((y%4==0)&&(y%100!=0))||(y%400==0));
}
//----------------------------------------------
long WeekdayOfYear(int y)
{
long TotalDay=0;
//求总天数
for (int i=1;i<=y;i++)
TotalDay+=365;
//加上闰年天数
for (int j=0;j<=y;j++)
TotalDay+=IsLeapYear(y);
TotalDay%=7;
return(TotalDay);
}