C++编写显示全年日历

源码下载链接:https://download.csdn.net/download/mr_xuf/10423884

#include <iostream>
#include <iomanip>
 
using namespace std;
 
class Calendar
{
private:
	int weekday;
	int year;
public:
	Calendar(int y);//构造函数(对私有变量进行初始化)
	void print_monthdays();//打印日期 
	void print_title(int m);//打印日历表头(一二三四五六日) 
	int monthdays(int n);//判断每个月的天数 
};
 
Calendar::Calendar(int y)
{
	year = y;
	weekday = (35+y+y/4-y/100+y/400)%7;
	if((year%4==0&&year%100!=0)||(year%400==0))  //判断是否闰年
	    weekday -= 1;
}
 
void  Calendar::print_monthdays()
{
	int days;
		 
	for(int n=1;n<13;n++)
	{
		print_title(n);//打印n月和表头 
		
		for(int i=0;i<weekday;i++)
			cout <<setw(4)<<" ";//每个月的1号对齐它的星期 
			
		days = monthdays(n);//返回月份天数 
		
		for(int i=1;i<=days;i++)
		{
			cout <<setw(4)<<i;  //设置输出的位宽 
			weekday = (weekday+1)%7;
			if(weekday==0) 
				cout <<endl;
		}
		cout <<endl<<"____________________________"<<endl;//每个月之间隔一空行 
	}
}
 
void Calendar::print_title(int m)
{		
	cout <<endl;
	cout<<"             "<<m <<"月"     <<endl;
	cout<<"----------------------------"<<endl;
	cout<<"  日  一  二  三  四  五  六"<<endl;
	cout<<"----------------------------"<<endl;
}
 
int Calendar::monthdays(int n)
{
	switch(n)
	{
		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((year%4==0&&year%100!=0)||(year%400==0))  //判断是否闰年
				return 29;//闰年 
			else
				return 28;//平年 
		}
		default: return 0;
	}
}
int main(void)
{
	int year;
 	
	cout <<"请输入你要查看的年份:";
	cin  >>year;
	Calendar A(year);
		
	cout <<endl<<year<<"年全年日历如下"<<endl;	
	
	A.print_monthdays();
	cout <<endl;
 
	return 0; 
}

上述程序的运行结果如下

欢迎大家加C/C++ Linux 技术栈开发群:786177639,一起交流学习

 

  • 15
    点赞
  • 57
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值