c - 请用C解释这个结构函数
问题描述
这是我正在做的一门课程的问题的解决方案。该作业要求创建一个函数,该函数返回一个包含以下日历日期的结构。我完全不知道这段代码是如何工作的。有人可以在声明数组后逐步分解它吗?
我特别不明白语法x.year==400
。公式是否不需要 a%400
来确定年份是否为闰年?
我也不知道什么if(x.day >array[x.month-1])
意思。这是在这个函数中声明的同一个“数组”吗?如果是这样,我认为它包含值“31、28....等”,而不是结构日期及其组件“月”。我真的不太了解它,所以欢迎任何反馈。
struct date advanceDay(struct date x)
{ // 'x' = whatever instance of 'struct date' is passed to function
int array[]= {31,28,31,30,31,30,31,31,30,31,30,31}; //number of days in each calendar month
if ((x.year%4 == 0 && x.year%100 != 0) || x.year==400) array [1] = 29; //Leap year formula on previous commentary
x.day++;
if (x.day > array[x.month-1]) {
x.month++;
x.day = 1;
}
if (x.month > 12) {
x.year++;
x.month = 1;
}
return x;
}
解决方案
您的函数将一天添加到 x。x = {31,01,2020}
让我们以2020 年 1 月 31 日的Let 为例。
第一条
if
语句检查是否x.year
是闰年,如果是闰年,则将天数更改为 29,array[1]
其中对应于二月。x.day++;
现在增加x.day
一x.day=32
。在这里array[x.month-1]=array[1-1]=array[0]=31
。第二条if
语句检查增量x.day
是否仍然是 的一天x.month
,这里x.day = 32
大于一月的天数。所以程序递增x.month
并设置x.day
为一。现在我们有x.day=01
和x.month=02
(二月)。最后一条
if
语句检查是否x.month
大于 12,这是一年的最大月数。如果它更高,则将其设置x.month
为 1(一月)并加x.month
一。我们的x.month=02
所以它不满足if
语句的条件。最后它返回
x={01,02,2020}
正确的第二天x={31,01,2020}
。
推荐阅读
- android - 是否可以检查是否启用了“显示布局边界”设置?
- sql - 创建具有不同条件 SQL 的 2 列的表
- c++ - 将 QPushButtons 数组连接到 lambda 函数 Qt 的问题
- github - 有没有一种方法可以在运行时动态地使 github 操作机密可用,而无需在 yaml 中显式定义每个变量?
- telegram - 电报机器人的新手
- mongodb - NestJS Mongo 引用未正确保存
- java - UDP 侦听器不接收数据
- git - 远程 Docker 容器内的 Github 访问(使用 2FA)
- c++ - 当我在控制台 C++ 程序中键入 STOP 时,我希望我的程序停止接受来自控制台的输入
- firebase - 如何在没有上下文的情况下使用提供者?