目录
项目分析
项目效果
头文件及全局变量
获取天数
打印月份、年份日历
main函数
#include
#include
#include
char g_week[7][10] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
char g_mon[13][10] = { "", "Janury", "February", "March", "April", "May", "June",
"July", "Auguet", "September", "October", "November", "December" };
bool LeapYear(int year)
{
return ((year % 4 == 0) && year % 100 != 0) || year % 400 == 0;
}
int GetMonDays(int year, int mon)
{
int days[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (mon == 2 && LeapYear(year))
return 29;
return days[mon];
}
int DaysGap(int year, int mon)
{
int days = 0;
int i = 1;
while (i < year)
{
if (LeapYear(i))
days += 366;
else
days += 365;
++i;
}
int j = 1;
while (j < mon)
{
days += GetMonDays(year, j);
++j;
}
return days;
}
项目的算法核心,年份的打印可以对月份打印进行嵌套循环打印
打印月份时对特殊节日进行标注
days是当月距离公元1年1月的天数差
ret值是days对7取余,得到当月的第一天是周几,ret是0则是周一,依此规则累加
void ShowMon(int year, int mon)
{
printf("\n %10s\n", g_mon[mon]);
printf("*---------*---------*---------*---------*---------*---------*---------*\n");
int i;
for (i = 0; i < 7; ++i)
printf("|%9s", g_week[i]);
printf("|\n");
for (i = 0; i < 7; ++i)
printf("|---------");
printf("|\n");
int days = DaysGap(year, mon);
int m_days = GetMonDays(year, mon);
int ret = days % 7;
for (i = 0; i < ret; ++i)
printf("| ");
int temp = 7 - ret;
for (i = 1; i <= m_days; ++i) {
if (mon == 1 && i == 1)
printf("|元旦节 %2d", i);
else if (mon == 6 && i == 1)
printf("|儿童节 %2d", i);
else if (mon == 10 && i == 1)
printf("|国庆节 %2d", i);
else
printf("|%9d", i);
if (i == temp || (i - temp) % 7 == 0)
{
printf("|\n");
int j;
for (j = 0; j < 7; ++j)
printf("|---------");
printf("|\n");
}
}
ret = (ret + m_days) % 7;
if (ret != 0)
{
printf("|\n");
int j;
for (j = 0; j < ret; ++j)
printf("|---------");
printf("|\n");
}
printf("\n");
}
void ShowYear(int year)
{
printf("\n***------***-----*** 万年历 (公元 %d 年) ***-----***------***\n", year);
int i = 1;
for (i = 1; i <= 12; ++i)
ShowMon(year, i);
}
void Menu()
{
printf("\n ***********************************************\n");
printf(" ****************** 1.查询年月 *************\n");
printf(" ****************** 2.查询年份 *************\n");
printf(" ****************** 0.退出查询 *************\n");
printf(" ***********************************************\n");
printf("请输入选项:");
}
int main()
{
int input;
do
{
Menu();
scanf("%d", &input);
int year, mon;
switch (input)
{
case 1:
system("cls");
printf("请输入要查询的年月: ");
scanf("%4d%2d", &year, &mon);
ShowMon(year, mon);
break;
case 2:
system("cls");
printf("请输入要查询的年份: ");
scanf("%4d", &year);
ShowYear(year);
break;
case 0:
printf("退出查询\n");
return 0;
default:
printf("输入错误,请重新输入\n");
}
} while (input);
return 0;
}