C语言日历

// 根据网友的一个问题整理的
// 输入年月,显示当前日历, 然后按下左右方向键会显示上个月或下个月的日历,按其他键两次退出

#include<stdio.h>   
#include<conio.h>
#include<dos.h>
#include<stdlib.h>

bool IsLeapYear(int year)   
{
	if ((0==year%4 && 0!=year%100) || 0==year%400)
	{
		return true;
	}
	else
	{
		return false;
	}
}   

int CalWkd(int year,int month)   
{   
	int total=0,i,rst,spaceWeek;
	int allMonths[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};

	if (IsLeapYear(year))
	{
		allMonths[2] = 29;
	}

	for (i=1; i<month; i++)
	{
		total += allMonths[i];
	}

	total += 1;
	rst = year-1+(int)((year-1)/4)-(int)((year-1)/100)+(int)((year-1)/400)+total;
	spaceWeek = rst%7;

	return spaceWeek;
}   

int ShowCalendar(int spaceWeek,int mtd)   
{   
	int dt = 1;
	int i = 0;
	int j = 0;
	printf("星期日\t星期一\t星期二\t星期三\t星期四\t星期五\t星期六\n");

	for (i=0; i<spaceWeek; i++)
	{
		printf("\t");
		j++;
	}
	while (j != 7)
	{
		printf("%d",dt);
		if (j < 6)
		{
			printf("\t");
		}
		else
		{
			printf("\n");
		}
		
		dt++;
		j++;
	}
	while (1)   
	{   
		for (j=0; j<7; j++)   
		{   
			printf("%d",dt);   
			if (j != 6)   
			{
				printf("\t");   
			}
			else   
			{
				printf("\n");   
			}

			if (dt != mtd)   
			{
				dt++;   
			}
			else   
			{
				return 0;   
			}
		}   
	}   
}   

int main(void)   
{
	int year,month,mtd,spaceWeek;
	int allMonths[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
	
	printf("input the year and month(year-month):\n");
	scanf("%d-%d",&year,&month); 

	do
	{
		if (year<0 || month<1 || month>12)  
		{
			return 0;   
		}
		
		if (IsLeapYear(year))   
		{
			allMonths[2] = 29;   
		}

		mtd = allMonths[month];   
		spaceWeek = CalWkd(year,month);   
		ShowCalendar(spaceWeek,mtd);   
		printf("\n");

		char ch1, ch2;
		ch1 = getch();
		ch2 = getch();
		if (ch2 == 0x4d)
		{
			month += 1;
		}
		else if (ch2 == 0x4b)
		{
			month -= 1;
		}
		else
		{
			printf("exit\n");
			break;
		}

		if (month > 12)
		{
			year += 1;
			month = 1;
		}
		else if (month < 1)
		{
			year -= 1;
			month = 12;
		}
		
		printf("%d-%d\n", year, month);
	}while (1);

	return 0;   
}  

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值