7、打印年历

打印年历:首先确定该年的元旦是星期几,然后循环12个月,每个月起始时打印星期,并设置日期的起始打印点,计算该月的天数(其中用到判断该年是否闰年),循环每个月中的天数,打印日期,逢7换行。打印格式如下:


               2000年

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

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

 

2月  日    一    二    三    四    五    六  

                      1      2      3   ……

 

 

源代码:

#include<iostream.h>

class Date{

private:

 int year;
 int month;
 int day;

public:

 Date(int y)
 {
  year = y;
  month = 1;
  day = 1;
 }

 Date(int y,int m)
 {
  year = y;
  month = m;
  day = 1;
 }

 Date(int y,int m,int d)
 {
  year = y;
  month = m;
  day = d;
 }

 int Getyear()   //取出年份
 {
      return  year;
 }

 int Getmonth()   //取出月份
 {
  return month;
 }

 int Getday()   //取出天
 {
  return day;
 }

 int Leapyear();   //判断是不是闰年

 int Week();  //求当前日期是星期几

 int Mathday();   //计算是一年中的第几天

};

 int Date::Leapyear()   //判断是不是闰年
 {

  if( (year%4 == 0 && year%100 != 0) || (year%4 == 0 && year%400 == 0) )
   return 1;
  else
   return 0;
 }

 int Date::Week()   //求当前日期是星期几
 {
  if( month == 1 || month == 2 )
  {
   year -= 1;
   month += 12;
  }
  return (day+1+2*month+3*(month+1)/5+year+(year/4)-year/100+year/400)%7;
 }
 
 int Date::Mathday()   //计算这天是一年中的第几天
 {
  int i = 0;
  int a = 0, b = 0;
  for(i=0; i < month; i++)
  {
   if(i==1 || i==3 || i==5 || i==7 || i==8 || i==10)
    a++;
  }
  if(month > 2)
  {
   if( year/4 == 0 || year/100 != 0 || year/4 == 0 && year/400 == 0 )
    b = 2;
   else
    b = 1;
  }
  return (day + (month-1)*30 + a - b);
 }

 void main()
 {
  cout<<"请输入您要打印的年:"<<endl;
  int y;
  cin>>y;
  cout<<endl;
  Date date(y);
  int a[12]={31,29,31,30,31,30,31,31,30,31,30,31};   //初始化一年这个中的每个月的天数
  if( date.Leapyear() != 1 )   //如果不是闰年,二月改为28天
  {
   a[1]=28;
  }
  cout<<" * * *   "<<date.Getyear()<<" 的 年 历"<<"   * * * "<<endl
   <<" = = = = = = = = = = = = = = = "<<endl<<endl;
  for(int i=0; i<12; i++)
  {
   cout<<" * "<<i+1<<"月"<<" * "<<endl;
   cout<<"日"<<"  "<<"一"<<"  "<<"二"<<"  "<<"三"<<"  "<<"四"<<"  "<<"五"<<"  "<<"六"<<endl;
   Date date02(y,i+1);
   int d = date02.Week();
   for(int j=0; j<d; j++)
   {
    cout<<"    ";
   }
   for(int k=0; k<a[i]; k++)
   {
    Date date03(y,i+1,k+1);
    if( date03.Getday() < 10 )
    {
     cout<<" ";
    }
    if(date03.Week() == 6)
    {
     cout<<k+1<<endl;
    }
    else
    {
     cout<<k+1<<"  ";
    }
   }
   cout<<endl<<endl;
  }
  return ;
 }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值