程序逻辑概述
根据平年闰年计算规则,利用递归先求出年份。之后再根据固定的大小月规则和平年闰年下2月天数的不同求出月数,之后就剩下最简单的天数、小时、分钟和秒了。
这个程序我承认为了尽可能缩小行数,有的地方写的不是很规范~正可谓是为了减少行数而不择手段~
程序代码
注:去掉空行的话的确只有35行的,我并不是标题党!
#include <iostream>
int time_stamp = 28800, year = 1969, month = 0, day = 0, hour = -1, minute = -1, tmp;
auto isLeapYear = [] { return (year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0) || (year % 3200 == 0 && year % 172800 == 0); };
int getYear(int *ptr_time_stamp) {
++year;
if (*ptr_time_stamp >= (isLeapYear() ? 31622400: 31536000))
getYear(&(*ptr_time_stamp -= (isLeapYear() ? 31622400 : 31536000)));
return year;
}
int getMonth(int *ptr_time_stamp) {
++month;
if (month == 2 && (*ptr_time_stamp >= (isLeapYear() ? 2505600 : 2419200)))
getMonth(&(*ptr_time_stamp -= (isLeapYear() ? 2505600 : 2419200)));
else if ((month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) && *ptr_time_stamp >= 2592000)
getMonth(&(*ptr_time_stamp -= 2678400));
else if ((month == 4 || month == 6 || month == 9 || month == 11) && *ptr_time_stamp >= 2678400)
getMonth(&(*ptr_time_stamp -= 2592000));
return month;
}
int getTime(int *ptr_time_stamp, int *type, int second) {
++*type;
if (*ptr_time_stamp >= second)
getTime(&(*ptr_time_stamp -= second), type, second);
return *type;
}
int main(void) {
std::cin >> tmp;
time_stamp += tmp;
std::cout << getYear(&time_stamp) << "年";
std::cout << getMonth(&time_stamp) << "月";
std::cout << getTime(&time_stamp, &day, 86400) << "日 ";
std::cout << getTime(&time_stamp, &hour, 3600) << "时";
std::cout << getTime(&time_stamp, &minute, 60) << "分" << time_stamp << "秒";
return 0;
}