码迷,mamicode.com
首页 > 其他好文 > 详细

[华为机试]输入一个正整数,输出2000年1月1日经过该整数天后的日期.

时间:2014-07-15 09:10:04      阅读:525      评论:0      收藏:0      [点我收藏+]

标签:使用   art   for   io   html   line   

//输入一个正整数,输出2000年1月1日经过该整数天后的日期.已测试,输入值可以为0~1095727
//如,100天后,日期为2000 4 10

#include<stdio.h>

#define MAX_YEAR 5000//年数可以从2000一直到4999年。

//函数功能:求解第year年共有多少天
int day_in_year(int year)
{
	if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
		return 366;
	else
		return 365;
}

int main()
{
	int input;
	int year, month, day;

	long Accumulate_days_for_year[MAX_YEAR] = {0};
	int Accumulate_days_for_month_in_leap_year[13] = {0,31,29,31,30,31,30,31,31,30,31,30,31};
	int Accumulate_days_for_month_in_aver_year[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
	int i;

	scanf_s("%d", &input);

	for (i = 2000; i < MAX_YEAR; i++)
	{
		Accumulate_days_for_year[i] = day_in_year(i);
	}
	for (i = 2001; i < MAX_YEAR; i++)
	{
		//该数组[2000]为366;[2001]为366+365,即2000年和2001年天数的累和;[2002]为366+365+365,即2000-2002年天数的累和。依次类推。
		//通过将累和与输入input比较,即可得知结果为哪一年。
		Accumulate_days_for_year[i] = Accumulate_days_for_year[i - 1] + Accumulate_days_for_year[i];
	}
	for (i = 2; i < 13; i++)
	{
		//该数组[1]为31;[2]为31+29,即1月和2月天数的累和;[3]为31+29+31,即1-3月天数的累和。依次类推。
		//通过累和判断结果为哪一月。
		Accumulate_days_for_month_in_leap_year[i] = Accumulate_days_for_month_in_leap_year[i] + Accumulate_days_for_month_in_leap_year[i - 1];
		//该数组[1]为31;[2]为31+28,即1月和2月天数的累和;[3]为31+28+31,即1-3月天数的累和。依次类推。
		//通过累和判断结果为哪一月。
		Accumulate_days_for_month_in_aver_year[i] = Accumulate_days_for_month_in_aver_year[i] + Accumulate_days_for_month_in_aver_year[i - 1];
	}

	//判断年数
	for (i = 2000; i < MAX_YEAR; i++)
	{
		if (input < Accumulate_days_for_year[i])
		{
			year = i;
			break;
		}
	}

	//得知年数后,通过下式判断结果为当年的第几天。
	input = input - Accumulate_days_for_year[year-1];

	//如果year为闰年,使用月累和数组Accumulate_days_for_month_in_leap_year
	if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
	{
		for (i = 1; i < 13; i++)
		{
			if (input < Accumulate_days_for_month_in_leap_year[i])
			{
				month = i;
				day = input - Accumulate_days_for_month_in_leap_year[i - 1] + 1;
				break;
			}
		}
	}
	//如果year为平年,使用月累和数组Accumulate_days_for_month_in_aver_year
	else 
	{
		for (i = 1; i < 13; i++)
		{
			if (input < Accumulate_days_for_month_in_aver_year[i])
			{
				month = i;
				day = input - Accumulate_days_for_month_in_aver_year[i - 1] + 1;
				break;
			}
		}
	}

	printf("%d\n", year);
	printf("%d\n", month);
	printf("%d\n", day);
	return 0;
}

[华为机试]输入一个正整数,输出2000年1月1日经过该整数天后的日期.,布布扣,bubuko.com

[华为机试]输入一个正整数,输出2000年1月1日经过该整数天后的日期.

标签:使用   art   for   io   html   line   

原文地址:http://www.cnblogs.com/Camilo/p/3841550.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!