问题描述
中国有句俗语叫“三天打鱼两天晒网”。某人从2010年1月1日起开始“三天打鱼两天晒网”,问这个人在以后的某一天中是“打鱼”还是“晒网”。用C或C++语言实现程序解决问题。
基本要求:1.程序风格良好(使用自定义注释模板),提供友好的输入输出。
提高要求:1.输入数据的正确性验证。
2.使用文件进行数据测试。如将日期 20100101 20111214 等数据保存在in.txt文件中,程序读入in.dat文件进行判定,并将结果输出至out.txt文件。
问题分析
这个问题可以分成几步走:
(1)计算从2010年1月1日到指定日期一共多少天
在计算中需要注意的点:计算每一年有多少天时我们需要分两种情况,闰年还有平年,闰年二月有29天,而平年二月有28天,分别对应一年366和365天。
(2)由于打鱼和晒网的周期是五天,所以用计算所得总天数除以五,得到余数。
(3)通过余数,判断是打鱼还是晒网,如果余数是1,2,3 其中一个,那就必然是打鱼,否则的话就是晒网。
(4)将测试日期存在in.txt中,查询结果放在out.txt中
流程图
代码实现
下面展示源代码。
#include <iostream>
#include <fstream>//文件操作
using namespace std;
struct Date //定义一个结构体来存储日期
{
int year;
int month;
int day;
}D;
int Judge(int year) //判断是否是闰年,是闰年返回1,否则返回0
{
int j;
if (year% 4 == 0 &&year% 100 != 0)
j = 1;
else if (year% 400 == 0)
j = 1;
else
j = 0;
return j;
}
int remainder(int year, int month, int day)//计算据2010年1月1日共多少天,赋值给r
{
int r = 0; //日期变量
int leapyear[12] = { 31,29,31,30,31,30,31,31,30,31,30,31 }; //闰年
int commonyear[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 }; //平年
for (int i = year; i != 2010; i--)
if (Judge(i) == 1)
r += 366;
else r += 365;
if (Judge(year) == 1)
for (int j = 0; j < (month - 1); j++)
r = r + leapyear[j];
else
for (int k = 0; k < (month - 1); k++)
r = r + commonyear[k];
r = r + day;
return(r);
}
int Islegal(int year,int month,int day) //判断日期是否合法
{
if (year < 2010 || month>12) //若输入年份小于2010,则返回0
return 0;
if (month == 2)
{
if (Judge(year) == 1 && day > 29)
return 0;
else
if (Judge(year) == 0 && day > 28)
return 0;
}
return 1;
}
int main()
{
int w;
bool k;
cout << "是否重新录入测试数据? 1-是,0-否"<<endl;
cin >> k;
if (k == 1)
{
cout << "请输入10组测试数据" << endl;
ofstream file("in.txt", ios::out);
if (!file)
{
cerr << "open error!" << endl;
exit(1);
}
for (int i = 0; i <10 ; i++)
{
cin >> D.year >> D.month >> D.day;
file << D.year << " " << D.month << " " << D.day << "\n";
}
file.close();
}
ifstream infile("in.txt", ios::out);//从文件中读取数据
ofstream ofile("out.txt", ios::app);//打开out.txt,将结果保存在该文件中
if (!infile|| !ofile)
{
cerr << "open error!" << endl;
exit(1);
}
for (int j = 0; j < 10; j++)
{
infile >> D.year >> D.month >> D.day;
if(Islegal(
D.year, D.month, D.day)==0)
ofile << D.year << " " << D.month << " " << D.day << "该日期非法!" << "\n";
else
{
w = remainder(D.year, D.month, D.day) % 5;
if (w == 1 || w == 2 || w == 3)
ofile << D.year << " " << D.month << " " << D.day << " 这一天在打渔!" << "\n";
else
ofile << D.year << " " << D.month << " " << D.day << " 这一天在晒网!" << "\n";
}
}
infile.close();
ofile.close();
system("pause");
return 0;
}