程式邏輯概述
根據平年閏年計算規則,利用遞迴先求出年份。之後再根據固定的大小月規則和平年閏年下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; }