九度OJ 1096:日期差值 (日期计算)

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:8138

解决:2752

题目描述:

有两个日期,求两个日期之间的天数,如果两个日期是连续的我们规定他们之间的天数为两天

输入:

有多组数据,每组数据有两行,分别表示两个日期,形式为YYYYMMDD

输出:

每组数据输出一行,即日期差值

样例输入:
20110412
20110422
样例输出:
11
来源:
2009年上海交通大学计算机研究生机试真题

思路:

直接相减需要考虑的情况比较多。比如找一个参考时间,比如00000101,算出两个日期与其差值,然后两个差值相减。


代码:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
 
#define N 10 
         
int compare(int y[2], int m[2], int d[2])
{       
    if (y[0] != y[1])
        return y[0]-y[1];
    else if (m[0] != m[1])
        return m[0]-m[1];
    else if (d[0] != d[1])
        return d[0]-d[1];
    else
        return 0;
}   
     
void swap(int a[2])
{   
    int tmp;
    tmp = a[0];
    a[0] = a[1];
    a[1] = tmp;
}   
 
int days(int y, int m, int d)
{
    int count = 0;
     
    //printf("y=%d, m=%d, d=%d\n", y, m, d);
     
    count += y*365;
    count += (y-1)/4+1;
    count -= (y-1)/100+1;
    count += (y-1)/400+1;
    //printf("count=%d\n", count);
                     
    if (m > 1)      
        count += 31;
    if (m > 2)
    {
        if ((y%4 == 0 && y%100 != 0) || y%400 == 0)
            count += 29;
        else
            count += 28;
    }
    if (m > 3)
        count += 31;
    if (m > 4)
        count += 30;
    if (m > 5)
        count += 31;
    if (m > 6)
        count += 30;
    if (m > 7)
        count += 31;
    if (m > 8)
        count += 31;
    if (m > 9)
        count += 30;
    if (m > 10)
        count += 31;
    if (m > 11)
        count += 30;
    if (m > 12)
        count += 31;
    //printf("count=%d\n", count);
 
    count += d;
    //printf("count=%d\n", count);
 
    return count;
}
 
int main(void)
{
    int i;
    char s[2][N], a[N];
    int y[2], m[2], d[2];
 
    while (scanf("%s%s", s[0], s[1]) != EOF)
    {
        for(i=0; i<2; i++)
        {
            strncpy(a, s[i], 4);
            a[4] = '\0';
            y[i] = atoi(a);
            strncpy(a, s[i]+4, 2);
            a[2] = '\0';
            m[i] = atoi(a);
            strncpy(a, s[i]+6, 2);
            a[2] = '\0';
            d[i] = atoi(a);
        } 
         
        printf("%d\n", abs(days(y[0], m[0], d[0]) - days(y[1], m[1], d[1])) + 1);
    }   
     
    return 0; 
}
/**************************************************************
    Problem: 1096
    User: liangrx06
    Language: C
    Result: Accepted
    Time:0 ms
    Memory:920 kb
****************************************************************/


你可能感兴趣的:(C语言,OJ,九度,日期计算)