(C++版本)根据用户输入的年份和月份,打印该月份的日历。
时间: 2024-06-09 07:11:45 浏览: 87
通过输入的年份和月份打印对应的日历
好的,以下是实现该功能的C代码:
```c
#include <stdio.h>
int main()
{
int year, month, days, week_day;
printf("请输入年份和月份(用空格分隔):");
scanf("%d%d", &year, &month);
// 计算该月份的天数
if (month == 2)
{
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
{
days = 29;
}
else
{
days = 28;
}
}
else if (month == 4 || month == 6 || month == 9 || month == 11)
{
days = 30;
}
else
{
days = 31;
}
// 计算该月份第一天是星期几
week_day = (year - 1) * 365 + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400;
for (int i = 1; i < month; i++)
{
if (i == 2)
{
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
{
week_day += 29;
}
else
{
week_day += 28;
}
}
else if (i == 4 || i == 6 || i == 9 || i == 11)
{
week_day += 30;
}
else
{
week_day += 31;
}
}
week_day = (week_day + 1) % 7;
// 输出日历头部
printf("日\t一\t二\t三\t四\t五\t六\n");
// 输出日历内容
int current_day = 1;
for (int i = 0; i < 6; i++)
{
for (int j = 0; j < 7; j++)
{
if (i == 0 && j < week_day)
{
printf("\t");
}
else if (current_day > days)
{
break;
}
else
{
printf("%d\t", current_day);
current_day++;
}
}
printf("\n");
if (current_day > days)
{
break;
}
}
return 0;
}
```
该程序首先让用户输入年份和月份,然后根据输入的年份和月份计算该月份的天数和该月份第一天是星期几,最后按照日历的格式输出该月份的日历。其中,计算该月份第一天是星期几的公式为:
```
week_day = (year - 1) * 365 + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400;
for (int i = 1; i < month; i++)
{
if (i == 2)
{
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
{
week_day += 29;
}
else
{
week_day += 28;
}
}
else if (i == 4 || i == 6 || i == 9 || i == 11)
{
week_day += 30;
}
else
{
week_day += 31;
}
}
week_day = (week_day + 1) % 7;
```
该公式中,首先计算出从公元元年到输入年份的天数,然后根据闰年规则调整天数(注意二月份的天数),最后加上该月份第一天的天数并对7取模,得到该月份第一天是星期几。
阅读全文