三天打鱼两天晒网
中国有句俗语叫“三天打鱼两天晒网”。某人从2010年1月1日起开始“三天打鱼两天晒网”,问这个人在以后的某一天中是“打鱼”还是“晒网”。这里使用C++来解决此问题。
代码:
/******************************/
//名称:三天打鱼两天晒网
//创作人:赵昱青
//创作时间:2018年8月30日
/******************************/
#include<iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
int num_days=0;//定义距离2010,1,1的总天数
int pingmonth[12] = {31,28,31,30,31,30,31,31,30,31,30,31 };//平年的各月天数
int runmonth[12]= { 31,29,31,30,31,30,31,31,30,31,30,31 };//闰年的各月天数
int year=0, month=0, day=0;//定义年月日int num_days = 0;
cout << "----------三天打鱼两天晒网------------------"<<endl;
/*cout << "请输入年份" << endl;
cin >> year;
cout << "请输入月份" << endl;
cin >> month;
cout << "请输入日" << endl;
cin >> day;
*/
//定义判断函数
int judge(int year);
//定义message变量 用来存储文件中读取到的数据
int message;
//相关文件操作 打开in.txt 和 out.txt
ifstream in("in.txt");
ofstream out;
out.open("out.txt");
//为了使读取的数据方便分辨出年月日这里文件中存储的数据格式为例:20101001 代表2010年10月1日,
//通过取余等相关操作分别给年月日进行赋值 来判断是打鱼还是晒网
//while函数保证将文档读取完全
while (!in.eof())
{
//文档读取到的数据为message
in >> message;
//为了使读取的数据方便分辨出年月日这里文件中存储的数据格式为例:20101001 代表2010年10月1日,
//通过取余等相关操作分别给年月日进行赋值 来判断是打鱼还是晒网
year = message / 10000;
month = (message % 10000) / 100;
day = message % 100;
//输入判断验证
if (year < 2010)
{
cout << "N输入错误!";
exit(0);
}
else if (month<1 || month>12)
{
cout << "Y输入错误!";
exit(0);
}
else if (judge(year) == 1)
{
if (day<1 || day>runmonth[month-1])
{
cout << "R输入错误!";
exit(0);
}
}
else if (judge(year) == 0)
{
if (day<1 || day>pingmonth[month-1])
{
cout << "R日期输入错误!";
exit(0);
}
}
//当为闰年时,通过闰年数组计算输入日期距离该年的天数
//日期=所输入的 天数+前面每月天数的和
if (judge(year) == 1)
{
for (int i = 0; i < month - 1; i++)
{
num_days += runmonth[i];
}
num_days += day;
}
//当为闰年时,通过平年数组计算输入日期距离该年的天数
//日期=所输入的 天数+前面每月天数的和
else
{
for (int i = 0; i < month - 1; i++)
{
num_days += pingmonth[i];
}
num_days += day;
}
//判断当前年份和2010年之间有相差的天数(此处并不计算当年的其余天数)
for (int i = 2010; i < year; i++)
{
if (judge(year) == 1)//当这一年是闰年的时候
num_days += 366;
else//当这一年是平年的时候
num_days += 365;
}
if (num_days % 5 <= 3 && num_days % 5 >= 1)
{
cout << year << " " << month << " " << day << " 今天捕鱼" <<endl;
out << year << " " << month << " " << day << " 今天捕鱼" << endl;
}
else
{
cout << year << " " << month << " " << day << " 今天晒网" << endl;
out << year << " " << month << " " << day << " 今天晒网" << endl;
}
num_days = 0;
}
//关闭文件
in.close();
out.close();
return 0;
}
//判断函数 用于判断是闰年还是平年
int judge(int year)
{
if (((year % 4) == 0 and (year % 100) != 0) || (year % 400 == 0))
{
return 1;
}
else
return 0;
}
设计思路:
这道题目的难点在于如何求出输入时间距离2010.1.1的日期,解决这个问题的关键在于判断在输入年份与2010年之间的年份是闰年还是平年。
首先定义一个judge()函数用来判断闰年平年,把所求的日期分为两个部分:
1.年日期。
2.月日期。
通过for循环从2010年开始遍历,判断出中间所有年的闰、平情况,闰年总天数为366,平年总天数为365,通过不断累加总天数得到年日期,之后计算月日期,首先判断闰、平年来判断2月的天数确定使用runmonth数组还是pingmonth数组,同理累加日期得到月日期,再加上day,再与年日期相加就得到了距离2010.1.1的总天数。
因为在三天打鱼两天晒网中,五天为一个周期,所以用总天数跟5取余,判断余数就能得出是打鱼还是晒网。
文件的使用:
文件的使用较为简单,详情请看代码注释。
流程图:
程序运行截图:
此程序基本功能已经实现,但是对于输入规范化方面仍有不足,将在继续改进。