阅读背景:

输入年月日, 计算该日是这一年中的第几天

来源:互联网 


/// @file exam_1_4.cpp
/// @brief 
/**
exam_1_4 *	定义一个包括年、月、日的结构体变量,当输入年、
月、日数据后,计算该日是这一年中的第几天。
*/

#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <crtdbg.h>

typedef struct _tag_DATE
{
    /// 年月日, 用户输入
    int iYear;
    int iMonth;
    int iDay;

    int iOffsetDay; ///< 一年中的第几天
}TAG_DATE;

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

void fnCalcYearMonthDay();
BOOL IsLeapYear(int iYear);
BOOL CalcDate(TAG_DATE* pDate);

int main(int argc, char *argv[ ], char *envp[ ])
{
    do 
    {
        fnCalcYearMonthDay();

        printf("'q' to quit, other key to play again\n");
        if ('q' == _getch())
        {
            break;
        }
    } while (1);

    printf("END, press any key to quit\n");
    getchar();
    
    return 0;
}

void fnCalcYearMonthDay()
{
    TAG_DATE date;

    printf("please input year:");
    scanf("%d", &date.iYear);
    fflush(stdin);

    printf("please input Month:");
    scanf("%d", &date.iMonth);
    fflush(stdin);

    printf("please input Day:");
    scanf("%d", &date.iDay);
    fflush(stdin);

    if (CalcDate(&date))
    {
        printf("date.iOffsetDay = %d\n", date.iOffsetDay);
    }
    else
    {
        printf("parameter is error, please try again\n");
    }
}

BOOL CalcDate(TAG_DATE* pDate)
{
    BOOL bRc = FALSE;
    BOOL bIsLeapYear = FALSE;
    int iMonthDayOffset = 0;
    int i = 0;
    
    do 
    {
        _ASSERT(NULL != pDate);
        pDate->iOffsetDay = 0;
        bIsLeapYear = IsLeapYear(pDate->iYear);
        
        if ((pDate->iMonth <= 0) || (pDate->iMonth > (sizeof(g_iArrMonthDay) /sizeof(int))))
        {
            break;
        }

        iMonthDayOffset = ((2 == pDate->iMonth) && bIsLeapYear) ? 1 : 0;
        if ((g_iArrMonthDay[pDate->iMonth - 1] + iMonthDayOffset) < pDate->iDay)
        {
            break;
        }

        for (i = 0; i < sizeof(g_iArrMonthDay) / sizeof(int); i++)
        {
            iMonthDayOffset = ((1 == i) && bIsLeapYear) ? 1 : 0;

            if (i == (pDate->iMonth - 1))
            {
                pDate->iOffsetDay += pDate->iDay;
                break;
            }
            else
            {
                pDate->iOffsetDay += g_iArrMonthDay[i] + iMonthDayOffset;
            }
        }

        bRc = TRUE;
    } while (0);

    return bRc;
}

BOOL IsLeapYear(int iYear)
{
    // 四年一闰,百年不闰,四百年再闰
    return (((0 == (iYear % 4)) && (0 != (iYear % 100))) || (0 == (iYear % 400)));
}/// @file exam_1_4.cpp
/// @brief 
/**
ex



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: