c-moodle/homework/11982.c

56 lines
1.7 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <stdio.h>
// 定义日期结构体类型
struct DATE {
int year; // 年
int month; // 月
int day; // 日
};
// 判断是否为闰年是则返回1否则返回0
int isLeapYear(int year) {
if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) {
return 1;
} else {
return 0;
}
}
// 返回指定年份和月份的天数
int daysOfMonth(int year, int month) {
int days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
if (isLeapYear(year) && month == 2) { // 如果是闰年并且是2月天数为29
return 29;
} else {
return days[month - 1]; // 返回对应月份的天数
}
}
// 在给定日期d的基础上加上k天
struct DATE adddays(struct DATE d, int k) {
d.day += k; // 先将天数加上k
while (d.day > daysOfMonth(d.year, d.month)) { // 如果天数大于该月份的天数
d.day -= daysOfMonth(d.year, d.month); // 减去该月份的天数
d.month++; // 月份加1
if (d.month > 12) { // 如果月份大于12年份也要加1
d.month = 1; // 月份从1开始
d.year++;
}
}
return d;
}
// 输出日期
void print(struct DATE d) {
printf("%d-%d-%d", d.year, d.month, d.day);
}
int main() {
struct DATE d1, d2;
int k;
scanf("%d %d %d", &d1.year, &d1.month, &d1.day); // 输入初始日期
scanf("%d", &k); // 输入加上的天数
d2 = adddays(d1, k); // 进行日期加上k天
print(d2); // 输出新的日期
return 0;
}