如何使用C中的结构正确地增加日期并输出以下日期



我正在练习C语言,并在网上找到了一些练习,所以我不得不写一个代码,它可以:

(1( 判断今年是否是一个飞跃

(2( 也许,日期本身必须在代码中定义

(3( 最后,根据给定的日期和函数IsLeapYear,程序应正确输出第二天的日期(如果需要,请更改年/月(:输入:2020-12-31输出:2021-01-01(NOT2020-12-32(

我在第三点上卡住了,我的代码不会改变年份/月份,这里我的代码是:

#include <stdio.h>
#include <math.h>
struct Date
{
int year;
int month;
int day;
};
typedef struct Date Date;
const int days[2][12] = {{31,28,31,30,31,30,31,31,30,31,30,31}//common year
,{31,29,31,30,31,30,31,31,30,31,30,31}};//leap year

int isLeapYear(int year)//year is leap or common
{
if(year%4==0&&year %100!=0 || year %400==0)
return 1;
else
return 0;
}
void increment(Date * p)
{
p->day++;
int leap=isLeapYear(p->year);
}
int main()
{
//p->year = 2021,p->month = 2,p->day = 28
Date today = {2021,12,31}; //2020 % 4 == 0 &&  2020 % 100 != 0
printf("%d-%02d-%02dn", today.year, today.month, today.day);
increment(&today);//2021-03-01 NOT 2021-02-29
printf("%d-%02d-%02dn", today.year, today.month, today.day);
return 0;
}

您已经拥有了所有的基本元素,您只需要根据您的"天";大堆展期还需要检查几个月的

void incrementMonth(Date * p){
p->month++;
if (p->month > 12){
p->month = 1;
p->year++;
}
}
void incrementDay(Date * p){
int leap=isLeapYear(p->year);
p->day++;
if (p->day > days[leap][p->month-1]){
p->day = 1;
incrementMonth(p);
}
}

您必须检查是否需要更新年/月。我建议用这种方法检查

void increment(Date * p) {
p->day++;
int leap=isLeapYear(p->year);
if (days[leap][p->month - 1] < p->day) {
p->day = 1;
p->month++;
}
if (p->month > 12) {
p->month = 1;
p->year++;
}
}

最新更新