C语言编程:定义一个结构体用于存储年、月、日数据,并定义一个函数用于求两个日期之间的天数。
1个回答
展开全部
#include <stdio.h>
const int days[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
struct Date
{
int year, month, day;
};
int DateCmp(Date a, Date b)
{
if (a.year != b.year)
return a.year > b.year;
if (b.month != a.month)
return a.month > b.month;
return a.day > b.day;
}
int isLunar(int year)
{
return year % 400 == 0 || (year % 100 && year % 4 == 0);
}
int DateDistace(Date a, Date b)
{
if (DateCmp(a, b))//保证a小于b
{
Date t = b;
b = a;
a = t;
}
//计算结果存储在res中
//首先计算相差的年
int i = a.year + 1, j = b.year - 1, res = a.year == b.year ? 0 : (j - i + 1) * 365;
for (int ii = (i + 3) / 4 * 4, jj = j / 4 * 4;ii <= jj;ii += 4, res++);
for (int ii = (i + 99) / 100 * 100, jj = j / 100 * 100;ii <= jj;ii += 100, res--);
for (int ii = (i + 399) / 400 * 400, jj = j / 400 * 400;ii <= jj;ii += 400, res++);
//然后计算相差的月
if (a.year != b.year)
{
for (int ii = a.month + 1;ii <= 12;ii++)
res += ii == 2 ? 28 + isLunar(a.year) : days[ii];
for (int ii = 1;ii <= b.month - 1;ii++)
res += ii == 2 ? 28 + isLunar(b.year) : days[ii];
}
else
{
for (int ii = a.month + 1;ii < b.month;ii++)
res += ii == 2 ? 28 + isLunar(a.year) : days[ii];
}
//最后计算相差的日
if (a.year != b.year || a.month != b.month)
{
res += (a.month == 2 ? 28 + isLunar(a.year) : days[a.month]) - a.day + b.day;
}
else
{
res += b.day - a.day;
}
return res;
}
int main()
{
Date a, b;
a.year = 2000; a.month = 12; a.day = 31;
b.year = 1000; b.month = 1; b.day = 1;
printf("%d\n", DateDistace(b, a));
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询