1

C语言每日一练——第133天:打鱼还是晒网

 2 years ago
source link: https://blog.csdn.net/m0_63325890/article/details/123271508
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Wassup guys,我是Edison😎

今天是C语言每日一练,第133天!

Let’s get it!
在这里插入图片描述





1. 问题描述

中国有句俗语叫 “ 三天打鱼两天晒网 ”。某人从 1990 年 1 月 1 日起开始 “三天打鱼两天晒网”,问这个人在以后的某一天中是 “打鱼” 还是 “晒网”。

2. 题目分析

根据题意可以将解题过程分为 3 步:

(1) 计算从 1990 年 1 月 1 日开始至指定日期共有多少天。

(2) 由于 “打鱼” 和 “晒网” 的周期为 5 天,所以将计算出的天数用 5 去除。

(3) 根据余数判断他是在 “打鱼” 还是在 “晒网”。

若余数为 1, 2, 3,则他是在 “打鱼”,否则是在 “晒网”。

3. 算法设计

该算法为数值计算算法,要利用循环求出指定日期距 1990 年 1 月 1 日的天数,并考虑到循环过程中的闰年情况,闰年二月为 29 天,平年二月为 28 天。

判断闰年的方法如下:

如果(能被 4 整除并且不能被 100 整除)或者(能被 400 整除)则该年是闰年;否则不是闰年。

提示:C语言中判断能否整除可以使用求余运算符 %

4. 流程框架

在这里插入图片描述

🍑 求出指定日期距离

这里为整个算法的核心部分,经过分析可以得到:

(指定日期距离 1990 年 1 月 1 日的天数)totalDay = 1990 年到指定年的前一年共有多少天 + 指定年中到指定日期的天数。

由于每月天数不同,可以设置一个月份数组int perMonth[13],存放每月的天数。

程序利用年份作为循环变量,要判断指定年份之前的每一年是否为闰年,若为闰年则执行totalDay=totalDay+366,否则执行 totalDay=totalDay+365

对于指定年份,也要判定是否为闰年,然后根据月份数,将每月的天数累加到 totalDay 中。

perMonth 数组的初始化设置如下图所示
在这里插入图片描述
perMonth 数组设置含有 13 个元素,perMonth[0]元素并不使用。

原因在于这种设置可以使数组下标和月份对应,便于编程设置循环变量,数组中 2 月天数初始设置为 28,如果当前年份为闺年,则需要执行 perMonth[2]++ 操作。

设计一个函数int run Year(int year) 来判断是否为闰年。

在这里插入图片描述

求总天数函数int countDay(Date currentDay)的实现。

在这里插入图片描述

5. 代码实现

完整代码📝

#include <stdio.h>

//定义日期结构体
typedef struct DATE
{
	int year;
	int month;
	int day;
}DATE;

//判断闰年函数
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,31 };

	int totalDay = 0;
	int i = 0;
	int year = 0;

	//求出指定日期之前的每一年的天数累加和
	for (year = 1990; year < currentDay.year; year++)
	{
		if (runYear(year))
		{
			totalDay = totalDay + 366;
		}
		else
		{
			totalDay = totalDay + 365;
		}
	}
	
	//如果为闰年,则2月份为29天
	if (runYear(currentDay.year))
	{
		perMonth[2]++;
	}

	//将本年内的天数累加到totalDay中
	for (i = 1; i < currentDay.month; i++)
	{
		totalDay += perMonth[i];
	}

	//将本月内的天数累加到totalDay中
	totalDay += currentDay.day;

	return totalDay;
}

int main()
{
	DATE today; //指定日期
	int totalDay; //指定日期距离1990年1月1日的天数
	int result; //totalDay对5取余的结果

	printf("请输入指定日期,包括年,月,日,例如:1999 1 31\n");
	printf("请输入>:");
	scanf("%d%d%d", &today.year, &today.month, &today.day);

	totalDay = countDay(today); //求出指定日期距离1990年1月1日的天数

	result = totalDay % 5; //天数%5 判断是打鱼还是晒网
	if (result > 0 && result < 4)
	{
		printf("今天打鱼\n");
	}
	else
	{
		printf("今天晒网\n");
	}
}
newCodeMoreWhite.png

运行结果👇

我们怎么判断出这个程序是正确的呢?

很简单,因为题目是从 1990 年 1 月 1 日开始的,那么1,2,3日肯定是 “打鱼” ;4,5日肯定是 “晒网”。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK