知今日,欲知三日后(三)

211 阅读2分钟

C语言趣味编程

已知今天日期,输出三天后的日期(三)

「这是我参与2022首次更文挑战的第3天,活动详情查看:2022首次更文挑战」。 编程很无趣,有趣的是我。

上期对2月份的天数这个变量呢作为一个函数写出来了,那么接下来处理第二个变量,每个月份的天数,该咋做呢?如果理解函数的话就直接讲函数返回值作为该变量就行,理解函数返回值的用法也非常重要,我们此处可以直接把该月份的天数作为返回值返回,同时因为涉及多个数据选择,我们可以构建一个数组来实现。

每个月的天数函数代码如下:


int daysOfMonth (struct date D){

    int num;

    int daysOfFeb (struct date D);

    const int daysPermonth[12]={31,28,31,30,31,30,31,30,31,31,30,31};

    if (today.month == 2)

         num = daysOfFeb (D);

    else num=daysPermonth[today.month-1];

    return num;

}

此处返回了每个不同月份对应的天数。

年份变量,月份天数变量已经解决了,那么关于日期中的day就可以确定了,还需要确定月份以及年份会不会有进位,所以,我们再添加一个进位的函数,或者,直接就可以说是日期变化函数,代码如下:


struct date addOne (struct date DD,int n){

    

    if (DD.month == 12)

    {   DD.year = DD.year + 131;

        DD.month = 1;

        DD.day = 3 - n;

    }

    else {DD.month = DD.month + 1;

          DD.day = 3 - n;

    }

        return DD;

        

}

那么日期具体如何变化的,这块我也说明不了,不啰嗦了,直接上代码结束今天,因为我感觉我也有点说不明白了,下期再具体做一个总结,收收尾。

整合代码如下所示:


#include <stdio.h>

#include <stdbool.h>

//create a struct of date that inlcude day,month,year

struct date{

    int day;

    int month;

    int year;

};

struct date today;

struct date afterThreeDays;

int daysOfFeb (struct date D){

int FebDays;

if ((D.year % 4 == 0 && D.year % 100 != 0) || (D.year % 400 == 0))

    FebDays = 29;

else FebDays = 28;

return FebDays;

}

int daysOfMonth (struct date D){

    int num;

    int daysOfFeb (struct date D);

    const int daysPermonth[12]={31,28,31,30,31,30,31,30,31,31,30,31};

    if (today.month == 2)

         num = daysOfFeb (D);

    else num=daysPermonth[today.month-1];

    return num;

}

//再编写一个进位的函数

struct date addOne (struct date DD,int n){

    

    if (DD.month == 12)

    {   DD.year = DD.year + 131;

        DD.month = 1;

        DD.day = 3 - n;

    }

    else {DD.month = DD.month + 1;

          DD.day = 3 - n;

    }

        return DD;

        

}

struct date result (struct date DD){

    int daysOfMonth (struct date D);

     

    struct date addYear (struct date DD,int n);

    if (( daysOfMonth(today)- today.day) >= 3)

    {   afterThreeDays.year = today.year;

        afterThreeDays.month = today.month;

        afterThreeDays.day = today.day + 3;

    }

    else if (( daysOfMonth(today) - today.day) == 2)

        afterThreeDays = addOne(today,2);

    else if(( daysOfMonth(today) - today.day) == 1)

        afterThreeDays = addOne(today,1);

    else if (( daysOfMonth(today) - today.day) == 0)

        afterThreeDays = addOne(today,0);

    return afterThreeDays;

}

int main (){

    struct date result (struct date DD);

    printf("plsae write values of the date of today:\n");

    scanf("%i:%i:%i",&today.day,&today.month,&today.year);

    afterThreeDays = result (today);

    printf ("%i:%i:%i\n",afterThreeDays.day,afterThreeDays.month,afterThreeDays.year);

    return 0;

}




程序实现结束,下期将会是精彩的总结。