C语言-求两个日期之间的距离

来源:互联网 发布:淘宝水印美图秀秀教程 编辑:程序博客网 时间:2024/05/17 01:00

下列代码的情况已确定第一个日期必定小于第二个日期,若不确定,可以将代码整理成一个函数,再写一个比较日期大小的函数来确定实参的位置,最后调用计算之间距离的函数,一样可以得到结果。


#include <stdio.h>#include <stdlib.h>#include<math.h>const int MONTH[2][12]= {{31,28,31,30,31,30,31,31,30,31,30,31},{31,29,31,30,31,30,31,31,30,31,30,31}};typedef struct data{    int year;    int month;    int day;} ;int Between(struct data data1,struct data data2);int isRun(int year);int main(){    struct data data1,data2;    int bew;    printf("请输入日期1(空格分隔,年 月 日):\n");    scanf("%d %d %d",&data1.year,&data1.month,&data1.day);    printf("请输入日期2(空格分隔,年 月 日):\n");    scanf("%d %d %d",&data2.year,&data2.month,&data2.day);    bew=Between(data1,data2);    printf("相差天数为:%d天",bew);    return 0;}int isRun(int year){    if(((year%400)==0)||(((year%4)==0)&&(year%100)!=0))return 1;    else return 0;}int Between(struct data dt1,struct data dt2){    int total =0;    while(dt1.year<dt2.year)    {        total+=365+isRun(dt1.year);        dt1.year++;    }    if(dt1.month<dt2.month)    {        while(dt1.month<dt2.month)        {            total+=MONTH[isRun(dt2.year)][dt1.month-1];            dt1.month++;        }    }    else if(dt1.month>dt2.month)    {        while(dt2.month<dt1.month)        {            total+=MONTH[isRun(dt2.year)][dt2.month-1];            dt2.month++;        }    }    if(dt1.day<dt2.day)    {        total+=dt2.day-dt1.day;    }    else if(dt1.day >dt2.day)    {        total+=dt1.day-dt2.day;    }    return total;}