实例说明
如果一个渔夫从 2011 年 1 月 1 日开始每三天打一次渔,两天晒一次网,编程实现当输入 2011 年1月1日以后的任意一天, 输出该渔夫是在打渔还是在晒网。
实现过程
(1)打开运行环境,新建一个源文件
(2)引用头文件
(3)自定义函数leap(), 用来判断输入的年份是否是闰年
(4)自定义函数 number(),用来计算输入日期距 2011 年1月1日共有多少天。
(5)main()函数作为程序的入口函数
#include <stdio.h>
typedef struct date
{
int year;
int month;
int day;
} DATE;
int countDay(DATE); //函数声明,计算在此期间共有的天数,在该函数中完成
int runYear(int); //判断是否为闰年,在该函数完成
int main()
{
DATE today; //将上面结构体函数名改为today
int totalday; //总天数
int result; //返回值处理totalday%5结果
printf("请输入指定的日期(如:2001 2 34):"); //
scanf("%d%d%d", &today.year, &today.month, &today.day);
totalday = countDay(today);
result = totalday % 5; //totalday % 5取余数,判断余数是否等于1,2,3在则输出打鱼,否则为晒网
if (result > 0 && result < 4) //判断余数
printf("%d年%d月%d日出海打鱼", today.year, today.month, today.day);
else
printf("%d年%d月%d日在家晒网", today.year, today.month, today.day);
return 0;
}
int runYear(int year)
{ // 能被4并且能被100整除的数或者能被400整除!否则为平年。
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
return 1;
else
return 0;
}
int countDay(DATE currentDay)
{
int perMonth[13] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; //一年中每个月的天数
int totalDay = 0, year, i;
for (year = 1990; year <= currentDay.year; year++)
{
if (runYear(year))
totalDay = totalDay + 366;
else
totalDay = totalDay + 365;
}
if (runYear(currentDay.year)) //判断输入的这一年是否为闰年,闰年2月则改变数组中的值+1天,变成29天
perMonth[2] += 1;
for (i = 0; i < currentDay.month; i++)
totalDay += perMonth[i];
totalDay += currentDay.day;
return totalDay;
}