c++下一天日期的nextDate()函数
时间: 2024-02-03 07:11:23 浏览: 58
下面是一个简单的C++代码示例,实现了一个nextDate()函数,用于计算给定日期的下一天日期:
```c++
#include <iostream>
using namespace std;
bool isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
}
int nextDate(int day, int month, int year) {
int daysInMonth[] = {31, 28 + isLeapYear(year), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (day < 1 || day > daysInMonth[month - 1] || month < 1 || month > 12) {
return -1;
}
if (day < daysInMonth[month - 1]) {
return day + 1;
} else {
if (month < 12) {
return 1;
} else {
return 1;
}
}
}
int main() {
int day, month, year;
cout << "Enter the date (dd mm yyyy): ";
cin >> day >> month >> year;
int next_day = nextDate(day, month, year);
if (next_day == -1) {
cout << "Invalid date!" << endl;
} else {
cout << "Next date is: " << next_day << " " << month << " " << year << endl;
}
return 0;
}
```
该程序首先检查输入的日期是否有效,如果无效则返回-1。否则,它将使用给定的月份和年份计算出该月的天数。如果输入的日期是该月的最后一天,则返回下一个月的第一天。否则,返回下一天的日期。
需要注意的是,此代码示例仅计算日期,未考虑时间和时区的影响。