繁琐日期计算模拟题。。一点一点慢慢写就行了,无技巧纯苦力活,网上能搜到测试数据,细心点就OK,话说测试数据好像有一条的格式化是错的,不用理会,大胆提交!
#include<stdio.h>
static int map[2][13] = { { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
{ 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } };
static char months[13][15] = { "", "January", "February", "March", "April",
"May", "June", "July", "August", "September", "October", "November",
"December" };
static char weekday[7][10] = { "Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday" };
static int is_leap(int year)
{
if (year <= 1752)
return year % 4 == 0;
else
return (year % 4 == 0 && year % 100) || year % 400 == 0;
}
static int is_valid(int year, int month, int day)
{
if (year != 1752)
return month >= 1 && month <= 12 && day >= 1
&& day <= map[is_leap(year)][month];
else if (month != 9)
return month >= 1 && month <= 12 && day >= 1 && day <= map[1][month];
else
return day == 1 || day == 2 || (day >= 14 && day <= 30);
}
static int before(int year, int month, int day)
{
int i, leap = is_leap(year), sum = 0;
for (i = 1; i < month; i++)
sum += map[leap][i];
return sum + day;
}
static int after(int year, int month, int day)
{
int i, leap = is_leap(year), sum = 0;
for (i = month + 1; i <= 12; i++)
sum += map[leap][i];
return map[leap][month] - day + sum;
}
int main()
{
int month, day, year;
int bb = before(1752, 9, 2), aa = after(1752, 9, 14);
while (scanf("%d %d %d", &month, &day, &year), month || day || year)
{
if (!is_valid(year, month, day))
{
printf("%d/%d/%d is an invalid date.\n", month, day, year);
continue;
}
int i, total = 0, res;
if (year < 1752)
{
total = after(year, month, day);
for (i = year + 1; i < 1752; i++)
total += is_leap(i) ? 366 : 365;
total += bb;
res = ((2 - total) % 7 + 7) % 7;
}
else if (year > 1752)
{
total = aa;
for (i = 1753; i < year; i++)
total += is_leap(i) ? 366 : 365;
total += before(year, month, day);
res = (total + 3) % 7;
}
else if (month < 9 || (month == 9 && day <= 2))
{
total = before(1752, 9, 2) - before(1752, month, day);
res = ((2 - total) % 7 + 7) % 7;
}
else
{
total = after(1752, 9, 14) - after(1752, month, day);
res = (total + 3) % 7;
}
printf("%s %d, %d is a %s\n", months[month], day, year, weekday[res]);
}
return 0;
}