【发布时间】:2020-07-24 08:24:02
【问题描述】:
这是我正在做的一门课程的问题的解决方案。该作业要求创建一个函数,该函数返回一个包含经过的以下日历日期的结构。我完全不知道这段代码是如何工作的。有人可以在声明数组后逐步分解吗?
我特别不明白x.year==400 的语法。该公式不需要%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.year==400”应该是“0 == x.year%400”。
-
如果我们检查一月,那么 x.month =1 ,我们需要检查数组[0]。所以“array[x.month-1]”是对的。