编写一个“日期推算”程序,该程序的功能是输入一个日期,输 出该日期后天的日期
时间: 2023-10-26 18:07:21 浏览: 114
下面是一个 C 语言程序,可以实现输入一个日期,输出该日期后天的日期:
```c
#include <stdio.h>
struct Date {
int year;
int month;
int day;
};
int is_leap_year(int year) {
return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
}
int get_days_of_month(int year, int month) {
int days_of_month[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (month == 2 && is_leap_year(year)) {
return 29;
}
return days_of_month[month];
}
struct Date get_tomorrow(struct Date date) {
int days_of_month = get_days_of_month(date.year, date.month);
if (date.day < days_of_month) {
date.day++;
} else {
date.day = 1;
if (date.month < 12) {
date.month++;
} else {
date.month = 1;
date.year++;
}
}
return date;
}
int main() {
struct Date date;
printf("Please enter a date (yyyy-mm-dd): ");
scanf("%d-%d-%d", &date.year, &date.month, &date.day);
struct Date tomorrow = get_tomorrow(date);
printf("The tomorrow is %04d-%02d-%02d\n", tomorrow.year, tomorrow.month, tomorrow.day);
return 0;
}
```
在此程序中,我们定义了一个名为 `Date` 的结构体,该结构体包含三个字段:`year`、`month` 和 `day`。我们还定义了两个辅助函数:
- `is_leap_year()`:判断某一年是否为闰年。
- `get_days_of_month()`:返回某一年某一月的天数。
在 `get_tomorrow()` 函数中,我们首先根据输入的年份和月份,获取该月的天数。然后判断输入的日期是否为该月的最后一天,如果是,则将月份加 1,如果该月已经是 12 月,则将年份加 1,月份重置为 1。最后,将日期加 1 并返回结果。
在 `main()` 函数中,我们首先提示用户输入一个日期,然后使用 `scanf()` 函数读取用户输入,并调用 `get_tomorrow()` 函数获取该日期的后天日期。最后,输出结果。