显示任意指定某年某月的月历(每天要有对应的星期)。用c++写一下这个程序
时间: 2023-05-19 16:01:11 浏览: 79
好的,以下是C知道为您提供的代码:
```c
#include <stdio.h>
int main() {
int year, month, days, week;
printf("请输入年份和月份,格式为yyyy mm:");
scanf("%d %d", &year, &month);
printf("%d年%d月的月历如下:\n", year, month);
printf("日 一 二 三 四 五 六\n");
// 计算该月的天数和第一天是星期几
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 = (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 += 29;
} else {
week += 28;
}
} else if (i == 4 || i == 6 || i == 9 || i == 11) {
week += 30;
} else {
week += 31;
}
}
week = (week + 1) % 7;
// 输出日历
for (int i = 0; i < week; i++) {
printf(" ");
}
for (int i = 1; i <= days; i++) {
printf("%2d ", i);
if ((i + week) % 7 == 0) {
printf("\n");
}
}
if ((days + week) % 7 != 0) {
printf("\n");
}
return 0;
}
```
这个程序可以让用户输入年份和月份,然后输出对应月份的日历,每天都有对应的星期。程序会自动判断该月的天数和第一天是星期几,然后输出日历。
阅读全文