【问题标题】:Please explain this structures function in C [closed]请用C解释这个结构函数[关闭]
【发布时间】: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]”是对的。

标签: c modulus


【解决方案1】:

您的函数将一天添加到 x。让我们举个例子 让x = {31,01,2020} 2020 年 1 月 31 日。

  • 第一个if 语句检查x.year 是否是闰年,如果是闰年,则将array[1] 中的天数更改为29,对应于2 月份。

  • 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 设置为1。现在我们有x.day=01x.month=02(2 月)。

  • 最后的if 语句检查x.month 是否大于12,这是一年的最大月数。如果它更好,则将x.month 设置为 1(一月)并将x.month 增加一。我们的x.month=02 所以它不满足if 语句的条件。

  • 最后它返回x={01,02,2020},它正确地是x={31,01,2020}的下一天。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多