记录一下日历的算法,从下午2点改到晚上8点Orz
题目:
Problem description |
A calendar is a system for measuring time, from hours and minutes, to months and days, and finally to years and centuries. The terms of hour, day, month, year and century are all units of time measurements of a calender system. According to the Gregorian calendar, which is the civil calendar in use today, years evenly divisible by 4 are leap years, with the exception of centurial years that are not evenly divisible by 400. Therefore, the years 1700, 1800, 1900 and 2100 are not leap years, but 1600, 2000, and 2400 are leap years. Given the number of days that have elapsed since January 1, 2000 A.D, your mission is to find the date and the day of the week. |
Input |
The input consists of lines each containing a positive integer, which is the number of days that have elapsed since January 1, 2000 A.D. The last line contains an integer −1, which should not be processed. You may assume that the resulting date won’t be after the year 9999. |
Output |
For each test case, output one line containing the date and the day of the week in the format of "YYYY-MM-DD DayOfWeek", where "DayOfWeek" must be one of "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" and "Saturday". |
Sample Input |
1730 1740 1750 1751 -1 |
Sample Output |
2004-09-26 Sunday 2004-10-06 Wednesday 2004-10-16 Saturday 2004-10-17 Sunday |
#include<iostream>
using namespace std;
#pragma warning(disable : 4996)
//这里写下month的二维数组,分别表示闰年平年,此后与is()全局函数联动,可以实现连续地循环
//day_of_year数组同理
//char数组不能用string类型,以后直接按照如下写法 char arrname[成员数][最长的字符串长度] = ....;
int month[2][13] = { {0,31,29,31,30,31,30,31,31,30,31,30,31},{0,31,28,31,30,31,30,31,31,30,31,30,31 } };
int day_of_year[2] = { 366,365 };
char week[8][10] = { "0","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"};
//返回星期数不一定要用函数,以后可以尝试多把数组当函数,简单快捷
int is(int days)
{
if ((days % 4 == 0 && days % 100 != 0) || (days % 400 == 0))
{
return 0;
}
else
{
return 1;
}
}
int main()
{
int n = 0;
while (scanf("%d",&n) && n != -1)//scanf括号中待输入的数为%d等形式,百分号在前,""外打逗号后,以引用的形式传值,勿忘!!
{
int year = 2000;
int mon = 1;
int day = 1 + n;//把第一天加上,小细节
//先计算year
day = 1 + n;
while (true)
{
if (day > day_of_year[is(year)])
{
//顺序很重要!!!
//不能先写year++,不然day的赋值表达式中的year会被影响,这里被WA导致浪费20min
day -= day_of_year[is(year)];
year++;
}
else
{
break;
}
}
//再计算日期
for (int i = 1; i <= 12; i++)
{
if (day > month[is(year)][i])
{
mon++;
day -= month[is(year)][i];
}
else
{
break;
}
}
printf("%d-%02d-%02d %s\n", year, mon, day, week[(n+5) % 7 + 1]);
}
return 0;
}
多多回味,受益良多。