Run ID:148089

提交时间:2026-02-09 16:46:41

#include <iostream> #include <iomanip> using namespace std; // 判断是否为闰年 bool isLeapYear(int year) { return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0); } // 获取某年某月的天数 int getDaysInMonth(int year, int month) { int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if (isLeapYear(year) && month == 2) { return 29; } return daysInMonth[month - 1]; } // 计算两个日期之间的天数差 int calculateDays(int birthYear, int birthMonth, int birthDay, int targetYear, int targetMonth, int targetDay) { int totalDays = 0; // 如果目标日期早于出生日期,则返回负数 if (targetYear < birthYear || (targetYear == birthYear && targetMonth < birthMonth) || (targetYear == birthYear && targetMonth == birthMonth && targetDay < birthDay)) { return -1; } // 先处理完整的年份 for (int year = birthYear; year < targetYear; year++) { totalDays += isLeapYear(year) ? 366 : 365; } // 减去出生当年未过的天数 for (int month = 1; month < birthMonth; month++) { totalDays -= getDaysInMonth(birthYear, month); } totalDays -= birthDay - 1; // 减去出生当天及之前的日子 // 加上目标年已过的天数 for (int month = 1; month < targetMonth; month++) { totalDays += getDaysInMonth(targetYear, month); } totalDays += targetDay; // 加上目标当天 return totalDays; } int main() { int T; cin >> T; for (int i = 0; i < T; i++) { int year, month, day; char dash1, dash2; // 用来读取 '-' 字符 cin >> year >> dash1 >> month >> dash2 >> day; // 计算18岁生日日期 int eighteenthBirthdayYear = year + 18; // 特殊情况处理: 出生于2月29日的人在非闰年的18年后没有2月29日 if (month == 2 && day == 29 && !isLeapYear(eighteenthBirthdayYear)) { cout << "-1" << endl; continue; } // 计算从出生到18岁生日的天数 int result = calculateDays(year, month, day, eighteenthBirthdayYear, month, day); cout << result << endl; } return 0; }