在程序设计中,日期时间的处理经常会遇到。在C语言程序设计的一些教材中会出现如下例子或习题。
【例1】第几天? (HDU 2005)
给定一个日期,输出这个日期是该年的第几天。
Input
输入数据有多组,每组占一行,数据格式为YYYY/MM/DD组成,具体参见sample input ,另外,可以向你确保所有的输入数据是合法的。
Output
对于每组输入数据,输出一行,表示该日期是该年的第几天。
Sample Input
1985/1/20
2006/3/12
Sample Output
20
71
(1)编程思路1。
对于month月,需要累计1~month-1月的各个月份的天数。例如,month等于8,需要累计1~7月的天数,即d=0+31(1月)+28(或29、2月天数)+31(3月)+30(4月)+31(5月)+30(6月)+31(7月),这个操作可以写成循环,如:
d=0;
for( i=1; i<=month-1; i++)
d=d+第i月的天数;
但也可以不写成循环,用switch…case结构来解决。因为,大的月份一定包含小的月份的累计,因此,在case常量表达式的安排时,可以从大到小,并且每个入口进入后,不用break语句退出switch结构,这样可以完成累计,具体描述为:
d=0;
switch(month-1)
{
case 11:d+=30;
case 10:d+=31;
case 9:d+=30;
case 8:d+=31;
case 7:d+=31;
case 6:d+=30;
case 5:d+=31;
case 4:d+=30;
case 3:d+=31;
case 2:d+=28(或d+=29);
case 1:d+=31;
}
另外,在程序中,需要判断某一年是否闰年,因为闰年的2月份为29天,而非闰年的2月份为28天。
闰年的判定条件是:①能被4整除,但不能被100整除的年份都是闰年,如1996年,2004年是闰年;②能被100整除,又能被400整除的年份也是闰年。如2000年是闰年。可以用一个逻辑表达式来表示:
(year%4==0&&year%100! =0) | | year%400==0
当year为某一整数值时,如果上述表达式值为true(1),则year为闰年;否则year为非闰年。
(2)源程序1。
#include <stdio.h>
int main()
{
int year,month,day,d;
while (scanf("%d/%d/%d",&year,&month,&day)!=EOF)
{
d=0;
switch(month-1)
{
case 11:d+=30;
case 10:d+=31;
case 9:d+=30;
case 8:d+=31;
case 7:d+=31;
case 6:d+=30;
case 5:d+=31;
case 4:d+=30;
case 3:d+=31;
case 2:d+=28;
if (year%4==0 && year%100!=0 || year%400==0) d++;
&nbs