C++求某日期的昨天、明天并判断两日期是否相等。
定义一个由年月日构成的日期类型,并设计函数实现以下操作:
①设计函数实现日期类型数据的初始化(三种方式实现:返回值、引用和指针法);
②为了保证输入的日期的合法性,要求设计一个函数对输入的日期进行正确性的检测;
③设计函数求某日期的昨天对应的日期;
④设计函数求某日期的明天对应的日期;
⑤设计函数判断两个日期是否相等。
#include <iostream>
#include <iomanip>
#include <stdlib.h>
using namespace std;
struct Date{
int year,month,day;
};
bool isLeap(int year){
return year%400||(year%4==0&&year%100!=0);
}
int getDayNumberDate(const Date d){
int num;
switch(d.month){
case 4:
case 6:
case 9:
case 11:
num=30;
break;
case 2:
if(isLeap(d.year)){
num=29;
}else{
num=28;
}
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
num=31;
}
return num;
}
bool checkDate(Date d){
bool flag=1;
if(d.year<1000||d.year>9999){
cout<<"输入的年号错误!"<<endl;
flag=0;
}else if(d.month<1||d.month>12){
cout<<"输入的月号错误!"<<endl;
flag=0;
}else{
int num=getDayNumberDate(d);
if(d.day<1||d.day>num){
cout<<"输入的日期错误!"<<endl;
flag=0;
}
}
return flag;
}
void input(Date &d)
{
do{
cout<<"请输入年月日:"<<endl;
cin>>d.year>>d.month>>d.day;
}while(!checkDate(d));
}
void output(const Date d)
{
cout<<d.year<<"年";
cout<<d.month<<"月";
cout<<d.day<<"日";
}
Date yesterday(Date d){
Date t;
t=d;
if(d.day>1){
t.day--;
}else {
if(d.month<=1){
t.month=12;
t.day=31;
t.year--;
}else{
t.month--;
t.day=getDayNumberDate(d);
}
}
return t;
}
Date tomorrow (Date d){
Date r;
r=d;
if(d.day<getDayNumberDate(d)){
r.day++;
}else{
r.day=1;
if(d.month<12){
r.month++;
}else{
r.month=1;
r.year++;
}
}
return r;
}
bool equal(Date t,Date d){
if(t.year==d.year&&t.month==d.month&&t.day==d.day){
cout<<"两个日期相等;"<<endl;
}else{
cout<<"两个日期不相等;"<<endl;
}
}
int main(){
Date d;
input(d);
cout<<"你输入的年月日为:"<<endl;
output(d);
cout<<endl;
Date d3;
d3=yesterday(d);
cout<<"昨天为:"<<endl;
output(d3);
cout<<endl;
Date d1;
d1=tomorrow(d);
cout<<"明天为:"<<endl;
output(d1);
cout<<endl;
Date d2;
input(d2);
equal(d2,d);
return 0;
}
运行结果:
还没有评论,来说两句吧...