題目鏈接:https://www.bilibili.com/video/av21356335?p=3
問題描述:某人從1999年1月1日起開始三天打魚兩天曬網,計算輸入的日期是打魚還是曬網
問題分析:
(1)先計算出輸入的日期距1990.01.01一共有多少天
(2)用計算出的天數去取餘5,根據結果判斷若餘數爲1,2,3則爲打魚,其他爲曬網
程序一:
#include<iostream>
using namespace std;
//判斷輸入的年份是否爲閏年
bool is_leap_year(int year)
{
if ((year%400==0) || ((year%100!=0)&&(year%4==0)))
{
return true;
}
return false;
}
//計算輸入的日期距離 1990 年 1 月 1 日一共多少天
int total_day(int year, int month, int day)
{
int total_num = 0;
int this_year = year;
int day_of_month[] = {31,28,31,30,31,30,31,31,30,31,30,31};
while(this_year>1990)
{
if(!is_leap_year(this_year))
{
total_num += 365;
}
else
{
total_num += 366;
}
this_year--;
}
for(int i = 1; i<month; i++)
{
total_num += day_of_month[i-1];
}
//若日期大於二月並且該年是閏年,總天數 + 1
if(month>2 && is_leap_year(year))
{
total_num++;
}
total_num += day;
return total_num;
}
int main()
{
cout<<"請輸入日期:"<<endl;
int year,month,day;
int total_number;
cin>>year;
cin>>month;
cin>>day;
total_number = total_day(year,month,day);
cout<<year<<"年"<<month<<"月"<<day<<"日距1990年1月1日一共有"<<total_number<<"天"<<endl;
int remainder = total_number % 5;
if(remainder==1 || remainder==2 || remainder==3)
{
cout<<"今天打魚!"<<endl;
}
else
{
cout<<"今天曬網!"<<endl;
}
return 0;
}
程序二:定義結構體存儲日期
#include<iostream>
using namespace std;
//定義日期結構體
typedef struct date{
int year;
int month;
int day;
}DATE;
//計算天數的函數聲明
int countDay(DATE);
//判斷是否爲閏年的函數聲明
int runYear(int);
int main(){
DATE today; //指定日期
int totalDay; //指定日期距 1990.01.01的天數
int result; //總天數對 5 取餘的結果
cout<<"輸入指定日期: "<<endl;
cin>>today.year;
cin>>today.month;
cin>>today.day;
totalDay = countDay(today);
cout<<"今天是第"<<totalDay<<"天"<<endl;
result = totalDay%5;
if(result>0&&result<4)
cout<<"今天打魚!"<<endl;
else
cout<<"今天曬網!"<<endl;
return 0;
}
//判斷是否爲閏年
int runYear(int year)
{
if((year%400==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,i,year;
for(year=1990;year<currentDay.year;year++)
{
if(runYear(year))
totalDay += 366;
else
totalDay += 365;
}
if(runYear(currentDay.year))
perMonth[2] = 29;
for(i=0;i<currentDay.month;i++)
totalDay += perMonth[i];
totalDay += currentDay.day;
return totalDay;
}