首页 > 解决方案 > 如何使用 C 中的结构正确增加日期并输出以下日期

问题描述

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

(1)判断年份是否为闰年

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

(3) 最后,根据给定的日期和函数IsLeapYear,程序应正确输出第二天的日期(如果需要,更改年/月): 输入:2020-12-31 输出:2021-01-01不是2020-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-%02d\n", today.year, today.month, today.day);

    increment(&today);//2021-03-01 NOT 2021-02-29
    printf("%d-%02d-%02d\n", today.year, today.month, today.day);
    return 0;
}

标签: c

解决方案


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

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++;
    }
}

推荐阅读