zoukankan      html  css  js  c++  java
  • 日期类问题-日期差值

    解题思想:把问题统一到特定日期与原点日期的天数差,分别求出两特定日期与原点日期的天数差,在将结果相减,便得到两特定日期天数差

    注:1.(能被4整除但不能被100整除)或(能被400整除)的年份为闰年。

    2.需要开辟大量内存空间的,必须在函数体外定义,即定义为全局变量,若在函数中会导致栈溢出,例如本题中:Time[5001][13][32]

    #include <stdio.h>
    
    int isLeapYear(int x){    //判断是否为闰年
        if( (x%4==0 && x%100!=0) || x%400==0)
            return 1;
        return 0;     
    }
    //每月的天数,后面为闰年 
    int dayOfMonth[13][2]={
        0,0,
        31,31,
        28,29,
        31,31,
        30,30,
        31,31,
        30,30,
        31,31,
        31,31,
        30,30,
        31,31,
        30,30,
        31,31,
    } ;
    
    struct Date{
        int day;
        int month;
        int year;
        
        void nextDay(){
            day++;
            if(day > dayOfMonth[month][isLeapYear(year)]){
                day = 1;
                month++;
                if(month > 12){
                    month = 1;
                    year++;
                }
            }
        }
    }; 
    int Time[5001][13][32];//保存天数
    int abs(int x){
        if(x < 0) return -x;
        return x;
    }
    
    int main(){
        Date time;
        int cnt=0;//天数计数 
        time.day=1;
        time.month=1;
        time.year=0;//初始日期为0年1月1日
        while(time.year!=5001){
            Time[time.year][time.month][time.day]=cnt;
            time.nextDay();
            cnt++;
        } 
        int y1,m1,d1;
        int y2,m2,d2;
        while(scanf("%4d%2d%2d",&y1,&m1,&d1) != EOF){
            scanf("%4d%2d%2d",&y2,&m2,&d2);
            int t= abs( Time[y1][m1][d1] - Time[y2][m2][d2])+1;
            printf("%d
    ",t);
        }
        return 0;
    }

    拓展:求某特定日期是该年的第几天?

    思想:该特定日期与原点日期的天数减去该年1月1日与原点日期的天数。

  • 相关阅读:
    Linux mysql 远程访问
    Linux下高并发socket最大连接数所受的各种限制
    Linux之gunzip命令
    不停在终端中报log
    FIO测试
    yum是什么?(linux命令)
    ubuntu grub 登录
    百度网盘命令行方式,解决ubuntu16.04百度网盘无法运行的问题
    excel使用经验汇总
    ubuntu 安装 ipfs 经验
  • 原文地址:https://www.cnblogs.com/chao-zjj/p/8278729.html
Copyright © 2011-2022 走看看