c - 如何使用 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;
}
解决方案
您必须检查是否需要更新年/月。我建议使用这种方法来检查
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++;
}
}
推荐阅读
- html - 是否可以相对于 div 缩放字体大小(不是视口)?
- java - 在 Java 8 流逻辑上需要帮助
- c# - 如何在 ASP.Net Core Razor 中使用 cookie 添加我自己的身份验证?
- java - java - 如何在Java中只显示退出迷宫的正确路线?
- angular - 将项目升级到 Angular 7 破坏了 Octopus 部署
- java - 在矩形上绘制文本
- python - 如何摆脱命令中多个单引号引起的语法错误
- sql - 连接多个值并在 null 时删除字符
- .net - 将文件从 Azure IaaS VM(文件存储)复制到 Azure PaaS 应用服务 (Blob)
- reactjs - 将函数组件作为渲染道具的参数传递