最近终于下定决心搞点小项目,练习自己的技术,做完了保存在这里,供大家交流。 以下程序完成一个日期到下次生日之间间隔的天数,可以直接运行。
#include<stdio.h>
#include <stdlib.h>
int Day[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
bool isLeap(int year)
{
return (year % 4 == 0 || year % 400 == 0) && (year % 100 != 0);
}
int daysInMonth(int year, int month)
{
if (isLeap(year))
{
Day[2] = 29;
}
return Day[month];
}
bool isLegal(int date[])
{
int year = date[0];
int month = date[1];
int day = date[2];
if (!isLeap(year))
{
return year > 0 && month > 0 && month <= 12 && day > 0 && day <= Day[month];
}
else
{
Day[2] = 29;
return year > 0 && month > 0 && month <= 12 && day > 0 && day <= Day[month];
}
}
void dateInput(int date[])
{
while (true)
{
scanf("%d.%d.%d", &date[0], &date[1], &date[2]);
if (isLegal(date))
{
break;
}
printf("输入日期不合法,请重新输入:\n");
}
}
int main()
{
int sum = 0, flag = 0;
int firstdate[3], seconddate[3];
printf("请输入当天日期(如:2021.12.2):\n");
dateInput(firstdate);
printf("请输入生日(如:2021.12.2):\n");
dateInput(seconddate);
if (seconddate[1] == 2 && seconddate[2] == 29)
{
while (!isLeap(firstdate[0]))
{
if (flag == 0)
{
for (int i = firstdate[1]; i <= 12; i++)
{
sum += daysInMonth(firstdate[0], i);
}
sum = sum - firstdate[2];
flag = 1;
firstdate[0]++;
continue;
}
if (flag == 1)
{
sum += 365;
firstdate[0]++;
}
}
if (flag == 0)
{
Day[2] = 29;
if (firstdate[1] < 2 || (firstdate[1] == 2 && firstdate[2] <= 29))
{
for (int i = firstdate[1]; i < seconddate[1]; i++)
{
sum += daysInMonth(firstdate[0], i);
}
sum = sum - firstdate[2] + seconddate[2];
}
else
{
for (int i = firstdate[1]; i <= 12; i++)
{
sum += daysInMonth(firstdate[0], i);
}
sum = sum - firstdate[2];
firstdate[0]++;
while (!isLeap(firstdate[0]))
{
sum += 365;
firstdate[0]++;
}
sum += 60;
}
}
if (flag == 1)
{
sum += 60;
}
}
else
{
if (firstdate[1] < seconddate[1] || (firstdate[1] == seconddate[1] && firstdate[2] <= seconddate[2]))
{
for (int i = firstdate[1]; i < seconddate[1]; i++)
{
if (isLeap(firstdate[0]))
{
Day[2] = 29;
sum += daysInMonth(firstdate[0], i);
}
else
{
sum += daysInMonth(firstdate[0], i);
}
}
sum = sum - firstdate[2] + seconddate[2];
}
else
{
for (int i = firstdate[1]; i <= 12; i++)
{
if (isLeap(firstdate[0]))
{
Day[2] = 29;
sum += daysInMonth(firstdate[0], i);
}
else
{
sum += daysInMonth(firstdate[0], i);
}
}
sum = sum - firstdate[2];
for (int i = 1; i < seconddate[1]; i++)
{
if (isLeap(firstdate[0] + 1))
{
Day[2] = 29;
sum += daysInMonth(firstdate[0], i);
}
else
{
sum += daysInMonth(firstdate[0], i);
}
}
sum = sum + seconddate[2];
}
}
printf("输入日期到下次生日 (%d.%d) 中间隔 %d 天。\n", seconddate[1], seconddate[2], sum);
system("pause");
return 0;
}
|