当前位置: 首页 > 工具软件 > leap-day > 使用案例 >

C - Write the routines day_of_year and month_day with pointers

罗翰
2023-12-01

分享一个大牛的人工智能教程。零基础!通俗易懂!风趣幽默!希望你也加入到人工智能的队伍中来!请点击http://www.captainbed.net

/*
 * Write the routines day_of_year and month_day with pointers.
 *
 * Tail.c - by FreeMan
 */

#include <stdio.h>
static char daytable[2][13] =
{
	{0, 31, 28, 31, 30, 31, 30, 31, 31, 30 ,31, 30, 31},
	{0, 31, 29, 31, 30, 31, 30, 31, 31, 30 ,31, 30, 31}
};

int day_of_year(int, int, int);
void month_day(int, int, int *, int *);

int main()
{
	int m, d;

	printf("day_of_year(2021, 1, 1) is %d\n", day_of_year(2021, 1, 1));
	printf("day_of_year(2021, 4, 3) is %d\n", day_of_year(2021, 4, 3));
	printf("day_of_year(2021, 12, 31) is %d\n", day_of_year(2021, 12, 31));

	month_day(2021, 1, &m, &d);
	printf("month_day(2021, 1) is: %d %d\n", m, d);
	month_day(2021, 100, &m, &d);
	printf("month_day(2021, 100) is: %d %d\n", m, d);
	month_day(2021, 365, &m, &d);
	printf("month_day(2021, 365) is: %d %d\n", m, d);

	return 0;
}

int day_of_year(int year, int month, int day)
{
	int leap;
	char *p;

	leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
	p = &daytable[leap][1];
	while (--month > 0)
	{
		day += *p++;
	}

	return day;
}

void month_day(int year, int dayofyear, int *pmonth, int *pday)
{
	int leap;
	char *p;

	leap = year % 4 == 0 && year % 100 != 0 || year % 400 == 0;
	p = &daytable[leap][1];
	while (dayofyear > *p)
	{
		dayofyear -= *p++;
	}
	*pmonth = 1 + p - &daytable[leap][1];
	*pday = dayofyear;
}

// Output:
/*
day_of_year(2021, 1, 1) is 1
day_of_year(2021, 4, 3) is 93
day_of_year(2021, 12, 31) is 365
month_day(2021, 1) is: 1 1
month_day(2021, 100) is: 4 10
month_day(2021, 365) is: 12 31

*/

 

 类似资料: