用C语言写一个日期计算器

  首先,我们应知道日期计算器包括哪些功能

1、明天的日期

2 、n天后的日期

3、两个日期之间的天数

我们先从第一个功能开始,首先创建一个日期的结构体,包括:年、月、日。

struct date
{
	int day;
	int month;
	int year;
};

其次来看一下解决这个问题的思想:

用C语言写一个日期计算器_第1张图片

然后我们要写一个判断闰年的函数:

int Leap(struct date d)
{
	int leap = false;
	if ((d.year % 4 == 0 && d.year % 100 != 0) || d.year % 400 == 0)
		leap = true;
	return leap;
}

上述代码中,我们需要先定义两个宏

#define true 1
#define false 0

假如是闰年,便返回1,否则返回0;

接下来,我们要写一个判断今天是否为本月的最后一天的函数:

int lastdays(struct date d)
{
	int days;
	int Month[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
	if (d.month == 2 && Leap(d))
		days = 29;
	else
		days = Month[d.month - 1];
	return days;
}

上面我们先定义了一个数组,里面是每个月的天数,其中二月有28,或者29天,我们在数组中定义二月为28天,然后判断本月是否为2月且是闰年,如果是,便返回29天,否则,返回每月的天数即可;

下面便是主函数了:

int main()
{
	struct date today, tomorrow;
	scanf("%d %d %d", &today.year, &today.month, &today.day);
	if (today.day != lastdays(today))
	{
		tomorrow.day = today.day + 1;
		tomorrow.month = today.month;
		tomorrow.year = today.year;
	}
	else if (today.month == 12) {
		tomorrow.day = 1;
		tomorrow.month = 1;
		tomorrow.year = today.year + 1;
	}
	else {
		tomorrow.day = 1;
		tomorrow.month = today.month + 1;
		tomorrow.year = today.year;
	}
	printf("%d %d %d", tomorrow.year, tomorrow.month, tomorrow.day);
	return 0;
}

其实当我们知道如何算明天的日期,后面两个问题也就迎刃而解了。对于第二个问题,只需要在主函数里面加循环就可以了,假如n为50的话,为非就是50个明天。

int main()
{
	struct date today, tomorrow;
	int n = 0;
	scanf("%d %d %d", &today.year, &today.month, &today.day);
	scanf("%d", &n);
	while (n != 0) 
	{
		if (today.day != lastdays(today))
		{
			tomorrow.day = today.day + 1;
			tomorrow.month = today.month;
			tomorrow.year = today.year;
		}
		else if (today.month == 12) {
			tomorrow.day = 1;
			tomorrow.month = 1;
			tomorrow.year = today.year + 1;
		}
		else {
			tomorrow.day = 1;
			tomorrow.month = today.month + 1;
			tomorrow.year = today.year;
		}
		n--;
		today.day = tomorrow.day;
		today.month = tomorrow.month;
		today.year = tomorrow.year;
	}
	printf("%d %d %d\n", tomorrow.year, tomorrow.month, tomorrow.day);
	return 0;
}

对于第三个问题,就是加一个判断,判断是否第二天是后面一天的日期,如果不是,就让count++:

int main()
{
	struct date today, tomorrow, hou;
	int count = 0;
	scanf("%d %d %d", &today.year, &today.month, &today.day);
	scanf("%d %d %d", &hou.year, &hou.month, &hou.day);
	while (hou.year!=today.year || hou.month!=today.month || hou.day!=today.day) 
	{
		if (today.day != lastdays(today))
		{
			tomorrow.day = today.day + 1;
			tomorrow.month = today.month;
			tomorrow.year = today.year;
		}
		else if (today.month == 12) {
			tomorrow.day = 1;
			tomorrow.month = 1;
			tomorrow.year = today.year + 1;
		}
		else {
			tomorrow.day = 1;
			tomorrow.month = today.month + 1;
			tomorrow.year = today.year;
		}
		today.day = tomorrow.day;
		today.month = tomorrow.month;
		today.year = tomorrow.year;
		count++;
	}
	printf("%d\n", count);
	return 0;
}
这便是一个简单的日期计算器。





你可能感兴趣的:(C语言)