5、设int year,month,day分别表示一个日期中的年月日,试编程求 a) 对于任意三个整数,判断其是否为一个合法的日期值。 b) 给定一个日期值,计算若干天后的日期值 c) 如果有两个日期值,计算他们相距的天数。
时间: 2024-05-09 13:17:47 浏览: 91
a)判断是否为合法日期:
```
bool isValidDate(int year, int month, int day) {
if (year < 0 || month < 1 || month > 12 || day < 1)
return false;
bool isLeap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
int maxDay = 31;
switch (month) {
case 2:
maxDay = isLeap ? 29 : 28;
break;
case 4:
case 6:
case 9:
case 11:
maxDay = 30;
break;
}
return day <= maxDay;
}
```
b)计算若干天后的日期值:
```
void addDays(int& year, int& month, int& day, int days) {
while (days > 0) {
int maxDays = daysInMonth(year, month);
int remainingDays = maxDays - day + 1;
if (remainingDays <= days) {
if (month == 12) {
year++;
month = 1;
} else {
month++;
}
day = 1;
days -= remainingDays;
} else {
day += days;
days = 0;
}
}
}
```
c)计算两个日期值之间的天数:
```
int daysBetween(int year1, int month1, int day1, int year2, int month2, int day2) {
// Convert to Julian day
int64_t julian1 = dateToJulian(year1, month1, day1);
int64_t julian2 = dateToJulian(year2, month2, day2);
// Calculate difference and return absolute value
return std::abs(julian1 - julian2);
}
int64_t dateToJulian(int year, int month, int day) {
return (1461 * (year + 4800 + (month - 14) / 12)) / 4
+ (367 * (month - 2 - 12 * ((month - 14) / 12))) / 12
- (3 * ((year + 4900 + (month - 14) / 12) / 100)) / 4
+ day - 32075;
}
```
希望能够帮到您。
阅读全文