数据连续化思想---判断一年中的第几天

普通代码实现(没用数据连续化思想):
#include <stdio.h>
int main(void)
{
    int m;
    int year,month,day;
    int GetDay(int y,int m,int d);
    printf("please input year and month and day:");
    scanf("%d %d %d",&year,&month,&day);
    m = GetDay(year,month,day);
    printf("Today is th year of %d day",m);
}
int GetDay(int y, int m, int d) //y年m月d日
{
    int s  = 0;
    switch(m-1)
    {
    case 1:
        s=31; break;
    case 2:
        s=31+28; break;
    case 3:
        s=31+28+31; break;
    case 4:
        s=31+28+31+30; break;
    case 5:
        s=31+28+31+30+31; break;
    case 6:
        s=31+28+31+30+31+30; break;
    case 7:
        s=31+28+31+30+31+30+31; break;
    case 8:
        s=31+28+31+30+31+30+31+31; break;
    case 9:
        s=31+28+31+30+31+30+31+31+30;
        break;
    case 10:
        s=31+28+31+30+31+30+31+31+30+31;
        break;
    case 11:
        s=31+           28+31+30+31+30+31+31+30+31+30;
        break;
    }
    if(m>2) //大于二月的话 看是否是闰年 如果是闰年 那要再加上一天
    {
        if(y%100==0&&y%4!=0||y%400==0)
        {
            s++;
        }
    }
    return s+d; //返回这天是那一年的第几天
}
看看上面糟糕的代码,是不是感觉代码量太多了
现在来看看用数据连续化思想:

#include <stdio.h>
int main(void)
{
    int m;
    int year,month,day;
    int GetDay(int y,int m,int d);
    printf("please input year and month and day:");
    scanf("%d %d %d",&year,&month,&day);
    m = GetDay(year,month,day);
    printf("Today is th year of %d day",m);
}
int GetDay(int y,int m,int d)
{
    int s = d;
    int List[12]={31,28,31,30,31,30,31,31,30,31,30,31};//把每个月比较特别的天数举出来
    if(y%400==0 || (y%100 && y%4==0))
    {
        ++List[1];//是的话2月多加一天
    }
      for(y=0,--m;y<m;++y)
    {
        s+=List[y];//直接累加
    }
    return s;
}



大家比较下吧!


原文链接: http://blog.csdn.net/crazyjixiang/article/details/6463827

你可能感兴趣的:(数据连续化思想---判断一年中的第几天)