中国有句俗语叫“三天打鱼两天晒网”。某人从1990年1月1日起开始“三天打鱼两天晒网”,问这个人在以后的某一天中是“打鱼”还是“晒网”。
根据题意可以将解题过程分为3步:
该算法为数值计算算法,要利用循环求出指定日期距1990年1月1日的天数,并考虑到循环过程中的闰年情况,闰年二月为29天,平年二月为28天。判断闰年的方法可以用伪语句描述如下:如果(能被4整除并且不能被100整除)或者(能被400整除)则该年是闰年;否则不是闰年。
判断是否为闰年流程图:
算法流程图:
下面是完整的代码:
- #include<stdio.h>
- /*定义日期结构体*/
- typedef struct date {
- int year;
- int month;
- int day;
- }DATE;
- int countDay(DATE currentDay); /*函数声明*/
- int runYear(int year); /*函数声明*/
- int main()
- {
- DATE today; /*指定日期*/
- int totalDay; /*指定日期距离1990年1月1日的天数*/
- int result; /*totalDay对5取余的结果*/
- /*输入指定日期,包括年,月,日*/
- printf("please input 指定日期 包括年,月,日 如:1999 1 31\n");
- scanf("%d%d%d", &today.year, &today.month, &today.day);
- totalDay=countDay(today); /*求出指定日期距离1990年1月1日的天数*/
- /*天数%5,判断输出打鱼还是晒网*/
- result=totalDay%5;
- if(result>0 && result<4)
- printf("今天打鱼");
- else
- printf("今天晒网");
- return 0;
- }
- /*判断是否为闰年,是返回1,否返回0*/
- int runYear(int year)
- {
- if( (year%4==0 && year%100!=0) || (year%400==0) ) /*是闰年*/
- return 1;
- else
- return 0;
- }
- /*计算指定日期距离1990年1月1日的天数*/
- int countDay(DATE currentDay)
- {
- int perMonth[13]={0,31,28,31,30,31,30,31,31,30,31,30}; /*每月天数数组*/
- int totalDay=0,year,i;
- /*求出指定日期之前的每一年的天数累加和*/
- for(year=1990; year<currentDay.year; year++)
- {
- if(runYear(year)) /*判断是否为闰年*/
- totalDay=totalDay+366;
- else
- totalDay=totalDay+365;
- }
- /*如果为闰年,则二月份为29天*/
- if(runYear(currentDay.year))
- perMonth[2]+=1;
- /*将本年内的天数累加到totalDay中*/
- for(i=0; i<currentDay.month; i++)
- totalDay+=perMonth[i];
- /*将本月内的天数累加到totalDay中*/
- totalDay+=currentDay.day;
- /*返回totalDay*/
- return totalDay;
- }
运行结果:
please input 指定日期 包括年,月,日 如:1999 1 31
2017 3 14↙
今天晒网