首页 > 解决方案 > 请用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;
}

标签: cmodulus

解决方案


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

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

  • x.day++;现在增加x.dayx.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=01x.month=02(二月)。

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

  • 最后它返回x={01,02,2020}正确的第二天x={31,01,2020}


推荐阅读