[题目要求] 某人三天打渔两天晒网,假设他从1990年1月1日开始打渔三天,然后晒网两天,请编程回答任意的一天他在打渔还是晒网。 A boy works for 3 days while has a 2 days off. If he is working on 1st, Jan, 1990, then for a date entered from the keyboard, please write a program to determine what the boy is doing, working or resting? Examples of input and output: 1)Input: 1990-01-05 Output: He is having a rest. 2)Input: 1990-01-07 Output: He is working. 3)Input: 1990-01-33 Output: Invalid input. ***输入数据格式***:"%4d-%2d-%2d" ***输出数据格式***:"Invalid input."或"He is having a rest." 或"He is working."
[程序代码]
#include<stdio.h>
#define OK 1
#define ERROR -1
#define Yes 1
#define No 0
#define working 1
#define resting 0
typedef short Status;
struct Date/* 日期信息 */
{
short year;
short month;
short day;
};
/* */
Status IsLeapYear(short year);
Status Input(struct Date *d1);
short LeapYearCount(short year1, short year2);
Status WorkingOrResting(struct Date *d1);
/* */
int main()
{
struct Date date;
if(Input(&date) == OK)
{
/* 输入信息合法 */
if(WorkingOrResting(&date) == working)
{
fprintf(stdout, "He is working.");
}
else
{
fprintf(stdout, "He is having a rest.");
}
}
return 0;
}
/* 判断是打渔还是晒网 */
Status WorkingOrResting(struct Date *d1)/* 要求给定信息合法 */
{
short leapyearInfo[12] = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335};
short commonyearInfo[12] = {0 ,31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
short year = d1 -> year;
short month = d1 -> month;
short day = d1 -> day;
/* 用这个年份和1990年1月1日作比较 */
short leapyearcount = LeapYearCount(1990, year);/* 求解1990年到给定年份间的闰年数 */
short commonyearcount = year - 1990 - leapyearcount;/* 求解1990年到给定年份间的平年数 */
long s;
if(IsLeapYear(year) == Yes)
{
s = 365 * commonyearcount + 366 * leapyearcount + leapyearInfo[month - 1] + day - 1;
}
else
{
s = 365 * commonyearcount + 366 * leapyearcount + commonyearInfo[month - 1] + day - 1;
}
if(s % 5 <= 2)
{
return working;
}
else
{
return resting;
}
}
/* 判断两个年份间有几个闰年年份 */
short LeapYearCount(short year1, short year2)/* year <= year2 */
{
short y = year1;
short leapyearcount = 0;
while(y < year2)
{
if(IsLeapYear(y) == Yes)
{
leapyearcount ++;
}
y ++;
}
return leapyearcount;
}
/* 判断给定年份是否为闰年 */
Status IsLeapYear(short year)
{
if(year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
{
/* 是闰年 */
return Yes;
}
else
{
/* 不是闰年 */
return No;
}
}
/* 输入日期信息 */
Status Input(struct Date* d1)
{
fscanf(stdin, "%4d-%2d-%2d", &d1 -> year, &d1 -> month, &d1 -> day);
if(d1 -> year < 1990)
{
fprintf(stdout, "Invalid input.");
return ERROR;
}
if(d1 -> month < 1 || d1 -> month > 12)
{
fprintf(stdout, "Invalid input.");
return ERROR;
}
if(IsLeapYear(d1 -> year) == Yes && d1 -> day > 31 || d1 -> day < 1)
{
fprintf(stdout, "Invalid input.");
return ERROR;
}
if(IsLeapYear(d1 -> year) == No && d1 -> day > 30 || d1 -> day < 1)
{
fprintf(stdout, "Invalid input.");
return ERROR;
}
/* 程序运行至此, 说明输入的信息已通过合法性检查 */
return OK;
}