用iostream设计一程序,输入一个年月日(2023 7 18),输出n天后的日期。
时间: 2023-09-22 08:01:43 浏览: 59
下面是一个使用iostream库设计的程序,可以接受一个年月日作为输入,并输出n天后的日期。
```c++
#include <iostream>
using namespace std;
// 判断闰年的函数
bool isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
return true;
else
return false;
}
// 获取某个月份的天数
int getDaysInMonth(int year, int month) {
int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 2 && isLeapYear(year))
return 29;
else
return days[month - 1];
}
// 获取n天后的日期
void getDateAfterNdays(int year, int month, int day, int n, int &newYear, int &newMonth, int &newDay) {
int daysInMonth = getDaysInMonth(year, month);
newYear = year;
newMonth = month;
newDay = day;
while (n > 0) {
if (newDay + n <= daysInMonth) {
newDay += n;
n = 0;
}
else {
n -= (daysInMonth - newDay + 1);
newDay = 1;
if (newMonth == 12) {
newYear += 1;
newMonth = 1;
}
else {
newMonth += 1;
}
daysInMonth = getDaysInMonth(newYear, newMonth);
}
}
}
int main() {
int year, month, day, n;
cout << "请输入年份:";
cin >> year;
cout << "请输入月份:";
cin >> month;
cout << "请输入日期:";
cin >> day;
cout << "请输入n的值:";
cin >> n;
int newYear, newMonth, newDay;
getDateAfterNdays(year, month, day, n, newYear, newMonth, newDay);
cout << "n天后的日期是:" << newYear << "年" << newMonth << "月" << newDay << "日" << endl;
return 0;
}
```
这个程序中,我们首先用isLeapYear函数判断输入的年份是否为闰年。然后,通过getDaysInMonth函数,获取输入的月份的天数。接着,使用getDateAfterNdays函数计算n天后的日期。在主函数中,我们通过iostream的输入输出流,让用户输入年份、月份、日期和n的值。然后,调用getDateAfterNdays函数得到n天后的日期,并输出到屏幕上。