求某一天是这一年的第几天(判断闰年)

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

用数组存储每月的天数

#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;
}

 

在C语言中,可以编写一段程序来计算给定日期是这一年第几天。基本思路包括以下步骤: 1. **确定是否为闰年**:判断该年份是否满足闰年条件(能被4整除但不能被100整除,或者能被400整除),以便正确设置二月份的天数。 2. **构建数组存储每月天数**:创建一个包含每个月标准天数的数组,并依据当前年份调整二月天数值。 3. **累加之前的月份天数并加上当月天数**:遍历目标日期前的所有月份数组元素并将它们相加以得出结果。 下面是一个示例代码片段展示如何实现上述功能: ```c #include <stdio.h> int isLeapYear(int year) { if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { return 1; } else{ return 0; } } int main() { int day, month, year; printf("请输入年、月、日:"); scanf("%d%d%d", &year, &month, &day); // 定义一年各个月的标准天数 int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; if(isLeapYear(year)){ daysInMonth[1] = 29; // 若是润年,则将2月设成29天 } int totalDays = 0; for(int i=0;i<month - 1;i++) { totalDays += daysInMonth[i]; } totalDays += day; printf("%d-%d-%d是一年的第%d天。\n", year, month, day,totalDays); } ``` 在这个例子中我们首先询问用户输入特定的一天,然后通过函数 `isLeapYear` 判断当年是不是闰年,并相应地修改了我们的“daysInMonth”数组值。最后循环累计所有过去的月份以及本月已过的日子总数就是我们要找的答案啦!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值