牛客网 华中科技大学 打印日期

题目描述

给出年分m和一年中的第n天,算出第n天是几月几号。

输入描述:

输入包括两个整数y(1<=y<=3000),n(1<=n<=366)。

输出描述:

可能有多组测试数据,对于每组数据,
按 yyyy-mm-dd的格式将输入中对应的日期打印出来。

示例1

输入

2000 3
2000 31
2000 40
2000 60
2000 61
2001 60

输出

2000-01-03
2000-01-31
2000-02-09
2000-02-29
2000-03-01
2001-03-01

答案

#include<stdio.h>

//判断是否为闰年
int isleapyear(int year)
{
    if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
    {
        return 1;
    }
    return 0;
}

int main()
{
    int i;
    int year, x;
    //累加法,分级别,以索引为月,以差值为日
    int leap[13] = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366};
    int noleap[13] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365};

    while(scanf("%d %d", &year, &x) != EOF)
    {
        //一年12for(i = 0; i < 13; i++)
        {
            //先看看是否为闰年
            if(isleapyear(year))
            {

                if(leap[i] >= x)
                {
                    printf("%04d-%02d-%02d\n", year, i, x - leap[i - 1]);
                    break;
                }

            }
            else 
            {
                if(noleap[i] >= x)
                {
                    printf("%04d-%02d-%02d\n", year, i, x - noleap[i - 1]);
                    break;
                }
            }
        }
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_37905259/article/details/81169511