头哥网第四关打印日历
#include <stdio.h>
#include <iostream>
using namespace std;
void printMonth(int year, int month);
int leapYear(int y)
{
if(y % 4 == 0 && y % 100 != 0 || y % 400 == 0)
return 1;
return 0;
}
int whatDay(int year, int month)
{
int w = 1;
int i;
for(i = 1; i < year; i++)
{
if(leapYear(i))
w += 366;
else
w += 365;
}
switch(month)
{
case 12:
w += 30;
case 11:
w += 31;
case 10:
w += 30;
case 9:
w += 31;
case 8:
w += 31;
case 7:
w += 30;
case 6:
w += 31;
case 5:
w += 30;
case 4:
w += 31;
case 3:
if(leapYear(year))
w += 29;
else
w += 28;
case 2:
w += 31;
case 1:
;
}
w = w % 7;
if(w == 0)
w = 7;
return w;
}
int month_day(int year, int month) {
switch (month)
{
case 2:
if (leapYear(year)) {
return 29;
}
else {
return 28;
}
break;
case 4:
case 6:
case 9:
case 11:
return 30;
break;
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
break;
default:
break;
}
}
void printMonth(int year, int month)
{
int days, day_week;
int i = 1;
int day = 1;
printf(" 一 二 三 四 五 六 日\n");
days = month_day(year, month);
day_week = whatDay(year, month);
if (day_week == 0) {
day_week = 7;
}
while (i < day_week) {
printf(" ");
i++;
}
while (day <= days) {
printf("%4d", day);
day++;
i = i % 7;
if (i == 0) {
printf("\n");
}
i++;
}
if (i != 0) {
printf("\n");
}
}
int main()
{
int y, m;
cin >> y >> m;
printMonth(y,m);
return 0;
}
可以不用我上述的代码来得到某月的第一天是星期几
int month_first_day_week(int year, int month) {
int week = 1;
for (int i = 1900; i < year; i++) {
++week;
if (isleap(i)) {
++week;
}
}
for (int i = 1; i < month; i++) {
week += month_day(year, i);
}
week %= 7;
return week;
}
这里可以直接得到某年某月的第一天是星期几。
|