“我們在一起99天是哪天呀?”
“說!今天是我們在一起多久了!”
“…”
源程式
直接初始化了原始日期,可自行更改。
可實作日期間的天數統計和數天的日期查詢。
黑闆程式
很久之前閑着沒事寫的。
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
int MonthDays[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
class Date
{ public:
Date(int a=3,int b=3,int c=2018);//初始日期是2018.3.3,構造函數 ;
void assign(int a,int b,int c);//指派函數 ;
void display();//輸出函數;
bool leap_year();//判斷是否是閏年(布爾);
void increment(int n);//目前日期n天後的日期;
int accumulate(Date& t);
private:
int day;
int month;
int year;
};
int Date::accumulate(Date& t)
{ int sum,n1,n2;
n1=MonthDays[month]-day;
while(t.year>year)// 2個日期“年”是否相同
{ if(leap_year()==0)
MonthDays[2]=28;
else
MonthDays[2]=29;
for(int i=month;i<12;i++)
{ n1+=MonthDays[i+1];
}
year+=1;
month=0;
}
if(leap_year()==0) //在同一年;
MonthDays[2]=28;
else
MonthDays[2]=29;
if(t.month>month)//不在同一個月;
{
for(int i=month;i<t.month-1;i++)
{ n1+=MonthDays[i+1];
}
n1+=t.day;
}
else
n1=t.day-day;
return n1;
}
Date::Date(int a,int b,int c)//構造函數;
{ day=a;
month=b;
year=c;
}
void Date::assign(int a,int b,int c)//指派函數;
{ day=a;
month=b;
year=c;
}
void Date::display()//輸出函數;
{ cout<<year<<"/"<<month<<"/"<<day<<endl;
cout<<"========================"<<endl;
}
bool Date::leap_year() //函數判斷是否是閏年;
{ return(year%4==0&&year%100!=0)||(year%400==0);//閏年的判斷條件;
}
void Date::increment(int n) //函數,計算n天後的日期 ;
{
while(n>=31)//加的天數大于一個月 ;
{
if(leap_year()==0)//不是閏年 ;
{ MonthDays[2]=28;
n=n-MonthDays[month];
month+=1;
if(month>12)
{month=month-12;
year+=1;}
}
else//是閏年 ;
{if(month<3)
MonthDays[2]=29;
n=n-MonthDays[month];
month+=1;
if(month>12)
{month=month-12;
year+=1;}
}
}
if(leap_year()==0)
{ MonthDays[2]=28;
day=day+n;
if(day>MonthDays[month])
{day=day-MonthDays[month];
month+=1;
if(month>12)
{month=month-12;
year+=1;}
}
}
else
{ if(month<3)
MonthDays[2]=29;
day=day+n;
if(day>MonthDays[month])
{day=day-MonthDays[month];
month+=1;
if(month>12)
{month=month-12;
year+=1;}
}
} }
int main()
{
int n,a1,b1,c1,a2,b2,c2,a;
/*date1.display();//輸出初始化;
date2.display();//輸出2018.3.3 ;*/
cout<<"親愛的使用者您好,現在預設的日期是2018.3.3"<<endl<<endl<<endl<<endl<<endl;
char m='y';
while(m=='y')
{ Date date1, date2(3,3,2018),date3,date4;
cout<<"☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆"<<endl<<endl;
cout<<"1.求相隔天數 2.求加n天後的日期"<<endl<<endl;
cout<<"☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆"<<endl<<endl<<endl;
cout<<"請選擇要執行的任務:";cin>>a;
if(a==1)
{
cout<<"請輸入另一個日期:(年/月/日)"<<endl;
cin>>a2>>b2>>c2;//輸入另一個日期;
date4.assign(c2,b2,a2);
cout<<"------------------------"<<endl;
cout<<"相隔的天數是:";
cout<<date2.accumulate(date4)<<endl;//計算之間的天數;
cout<<"========================"<<endl;}
if(a==2)
{
cout<<"請輸入初始日期:(年/月/日)"<<endl;
cin>>a1>>b1>>c1;//輸入一個日期;
date3.assign(c1,b1,a1);
cout<<"------------------------"<<endl;
cout<<"請輸入天數:"<<endl;
cin>>n;//輸入一個天數;
date3.increment(n);//計算該天數之後的日期;
cout<<"累加後的日期是:(年/月/日)"<<endl;
date3.display();//顯示該天數之後的日期;
}
cout<<"★★★★★★★★★★★★"<<endl;
cout<<"========================"<<endl;
cout<<"是否繼續輸入?(y/n)"<<endl;
cin>>m;
}
return 0;
}