输入一个正整数,输出2000年1月1日经过该整数天后的日期.

本文介绍了一个C语言程序,用于计算从2000年1月1日起任意天数后的具体日期。程序考虑了闰年和平年的差异,通过累积天数和每月天数来精确确定目标日期的年、月、日。
//输入一个正整数,输出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;
}

转载于:https://www.cnblogs.com/Camilo/p/3841550.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值