酷代码 AI
菜单
服务商

C++ 实现:输入年月日,精准计算 n 天后的日期!

以下是使用 C++ 实现计算 n 天后日期的代码: ```cpp #include <iostream> // 判断是否为闰年 bool isLeapYear(int year) { return (year % 4 == 0 && year % 100!= 0) || year % 400 == 0; } // 获取每个月的天数 int daysInMonth(int month, int year) { int days; switch (month) { case 2: days = isLeapYear(year)? 29 : 28; break; case 4: case 6: case 9: case 11: days = 30; break; default: days = 31; } return days; } int main() { int year, month, day, n; std::cin >> year >> month >> day >> n; while (n > 0) { int daysInCurrentMonth = daysInMonth(month, year); if (day + n <= daysInCurrentMonth) { day += n; n = 0; } else { n -= (daysInCurrentMonth - day + 1); day = 1; if (month == 12) { year++; month = 1; } else { month++; } } } std::cout << year << "-" << month << "-" << day << std::endl; // 注意点: // 1. 处理闰年时要准确判断 2 月份的天数。 // 2. 月份和日期的范围要进行有效判断和处理。 // 3. 输入的年份、月份、日期和 n 要进行有效性验证。 return 0; } ``` ######[AI写代码神器 | 436点数解答 | 2025-02-28 17:21:56]

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