酷代码 AI
菜单
服务商

C++ 代码:从儒略日精准计算公历日期及复杂度分析

以下是解决该问题的 C++ 代码: ```cpp #include <iostream> #include <vector> using namespace std; // 判断是否为闰年 bool isLeapYear(int year, bool isGregorian) { if (isGregorian) { return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0); } if (year > 0) { return year % 4 == 0; } else { return (-year - 1) % 4 == 0; } } // 每个月的天数 int monthDays[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // 根据儒略日计算公历日期 string calculateDate(long long julianDay) { int year = -4713; // 起始年份 int month = 1; int day = 1; // 公元前 4713 年 1 月 1 日到 1582 年 10 月 4 日 while (julianDay > 0) { int daysInYear = 365; if (isLeapYear(year, false)) { daysInYear = 366; } if (year == 1582) { daysInYear = 355; // 1582 年特殊处理,少 10 天 } if (julianDay >= daysInYear) { julianDay -= daysInYear; year++; } else { break; } } // 处理 1582 年 10 月特殊情况 if (year == 1582) { if (julianDay > 277) { // 10 月 15 日及以后 julianDay += 10; } } // 处理月份和日期 while (julianDay > 0) { int daysInMonth = monthDays[month]; if (month == 2 && isLeapYear(year, year >= 1582)) { daysInMonth = 29; } if (julianDay >= daysInMonth) { julianDay -= daysInMonth; month++; if (month > 12) { month = 1; year++; } } else { day = julianDay; julianDay = 0; } } // 格式化输出 string result; if (year <= 0) { result = to_string(day) + " " + to_string(month) + " " + to_string(-year) + " BC"; } else { result = to_string(day) + " " + to_string(month) + " " + to_string(year); } return result; } int main() { int Q; cin >> Q; vector<long long> r(Q); for (int i = 0; i < Q; i++) { cin >> r[i]; } for (int i = 0; i < Q; i++) { cout << calculateDate(r[i]) << endl; } return 0; } ``` 代码说明: 1. `isLeapYear` 函数:用于判断给定年份是否为闰年。根据是否采用格里高利历,有不同的判断规则。 2. `monthDays` 数组:存储每个月的天数。 3. `calculateDate` 函数:根据输入的儒略日计算对应的公历日期。 - 首先处理公元前 4713 年 1 月 1 日到 1582 年 10 月 4 日的情况,逐年减去天数,直到剩余天数不足以减去一整年。 - 对于 1582 年 10 月的特殊情况,进行额外处理。 - 然后逐月减去天数,直到剩余天数不足以减去一个月,确定月份和日期。 - 最后根据年份是否为公元前,格式化输出结果。 4. `main` 函数:读取输入的询问组数 `Q` 和每个儒略日,调用 `calculateDate` 函数计算并输出对应的公历日期。 复杂度分析: - 时间复杂度:$O(Q \times Y)$,其中 $Q$ 是询问的组数,$Y$ 是平均需要处理的年数。 - 空间复杂度:$O(Q)$,主要用于存储输入的儒略日。 ######[AI问答 | 1156点数解答 | 2026-02-08 19:36:11]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]