简答题
偏难
#20106
日历制作
日历制作


答案与解析
正确答案:<pre class="brush:cpp;toolbar:false">#include <algorithm>
#include <cstdio>
using namespace std;
// 下标0占位,1~12对应1-12月平年天数
int days[20] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int main() {
int m;
scanf("%d", &m);
// 打印星期表头
printf("MON TUE WED THU FRI SAT SUN\n");
int total_day = days[m];
int week = 1; // 基准:9月1日为星期一
// 分两种情况偏移计算当月1号星期
if (m > 9) {
// 月份在9月之后:向后累加天数偏移
for (int i = 9; i < m; i++) {
week = (week + days[i] - 1) % 7 + 1;
}
} else if (m < 9) {
// 月份在9月之前:向前倒推天数偏移
for (int i = 8; i >= m; i--) {
week = ((week - days[i]) % 7 + 7) % 7;
}
if (week == 0) week = 7;
}
// 打印1号前面的空白占位
for (int i = 1; i < week; i++) {
printf(" ");
}
// 逐行打印日期
for (int day = 1; day <= total_day; day++) {
printf("%3d", day);
week = week % 7 + 1;
// 到周日或当月最后一天,换行
if (week == 1 || day == total_day) {
printf("\n");
} else {
printf(" ");
}
}
return 0;
}</pre>
这道题暂未补解析。