For a given year, month and day, calculate it as the day of the year

According to the following function prototype, use functional programming to solve the following date conversion problem (requires to consider the problem of leap year):
input a certain day of a certain month and a certain day, calculate and output it is the day of the year.
/* Function: For a given
year, month, and day, calculate it as the day of the year. Function parameters: Integer variables year, month, and day, representing the year, month, and day respectively.
Function return value: this The day of the year*/
int DayofYear(int year, int month, int day);
Input prompt information: "Please enter year, month, day:"
Input format: "%d,%d,%d"
Output prompt Information and format: "yearDay = %d\n"

Solution: First judge the leap year in the cal function, and use an array to store the number of days in each month for easy calculation. Then use February as the limit to calculate the total number of days. Before returning the calculated value, it changes according to the leap year or not.

#include<stdio.h>
int cal(int year, int month, int day);
int main(void)
{
    
    
	int year, month, day;
	printf("Please enter year, month, day:");
	scanf_s("%d,%d,%d", &year, &month, &day);
	int res;
	res = cal(year, month, day);
	printf("yearDay = %d\n", res);
}
int cal(int year, int month, int day)
{
    
    
	int leap = 0;
	int total;
	int md[12] = {
    
     31,28,31,30,31,30,31,31,30,31,30,31 };
	if (month >= 2)
	{
    
    
		if (year % 4 == 0)
		{
    
    
			if (year % 100 != 0)
			{
    
    
				leap = 1;
			}
			else if (year % 400 == 0)
			{
    
    
				leap = 1;
			}
		}
		switch (month)
		{
    
    
		case 2: total = md[0] + day; break;
		case 3: total = md[0] + md[1] + day; break;
		case 4: total = md[0] + md[1] + md[2] + day; break;
		case 5: total = md[0] + md[1] + md[2] + md[3] + day; break;
		case 6: total = md[0] + md[1] + md[2] + md[3] + md[4] + day; break;
		case 7: total = md[0] + md[1] + md[2] + md[3] + md[4] + md[5] + day; break;
		case 8: total = md[0] + md[1] + md[2] + md[3] + md[4] + md[5] + md[6] + day; break;
		case 9: total = md[0] + md[1] + md[2] + md[3] + md[4] + md[5] + md[6] + md[7] + day; break;
		case 10:total = md[0] + md[1] + md[2] + md[3] + md[4] + md[5] + md[6] + md[7] + md[8] + day; break;
		case 11:total = md[0] + md[1] + md[2] + md[3] + md[4] + md[5] + md[6] + md[7] + md[8] + md[9] + day; break;
		case 12:total = md[0] + md[1] + md[2] + md[3] + md[4] + md[5] + md[6] + md[7] + md[8] + md[9] + md[10] + day;
		}
		if (leap == 1)
			total++;
		return total;
	}
	else
	{
    
    
		return day;
	}
}

running result:Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_43888800/article/details/110056059