求某一天是这一年的第几天

用结构体实现今天是这一年的第几天

用数组存储每月的天数

#include <stdio.h>

typedef struct Day
{
	int year;
	int month;
	int day;
}Day;
bool IsLeapYear(int n)//判断是否是闰年
{
	return (n%4==0&&n%100!=0||n%400==0);
}
int GetDay (const Day*pday)
{
	int count=0;
	int arr[]={31,28,31,30,31,30,31,31,30,31,30,31};//用数组存储数据
	if(IsLeapYear (pday->year ))
	{
		arr [1]=29;
	}
	for(int i=0;i<pday->month-1;i++)
	{
		count+=arr[i];
	}
	count+=pday->day;
	return count;
}

int main()
{
	Day d1[]={2018,1,1};
	Day d2[]={2020,3,1};
	printf("%d\n",GetDay (d1));
	printf("%d\n",GetDay (d2));
	return 0;
}
#include <stdio.h>
typedef struct Date//定义结构体存放日期
{
	int month;
	int day;
	int year;
}Date;
void Days(Date *p)
{
	int count=0;//计数器
	if((*p).year %4 ==0 &&(*p).year % 100 !=0||(*p).year%400==0)//判断是否是闰年
	{
		for(int i=1;i<(*p).month ;i++)
		{
			if(i==1||i==3||i==5||i==7||i==8||i==10)
			{
				count+=31;
			}
			else if(i==2)
			{
				count+=29;
			}
			else 
				count+=30;
		}
		count += (*p).day;
	}
	else
	{
		for(int i=1;i<(*p).month ;i++)
		{
			if(i==1||i==3||i==5||i==7||i==8||i==10)
			{
				count+=31;
			}
			else if(i==2)
			{
				count+=28;
			}
			else 
				count+=30;
		}
		count += (*p).day;
	}
	printf("%d\n",count);
}

int main()
{
	Date str1[]={7,26,2018};
	Date str2[]={1,1,2018};
	Date str3[]={12,31,2018};
	Date str4[]={12,31,2016};
	Days (str1);
	Days (str2);
	Days (str3);
	Days (str4);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/like_that/article/details/83120139