一.题目: C++编写程序:前一日函数PreDate。实现功能为:输入1000 年到2020 年之间的某个日期(20180412),函数返回这一天的前一天的日期。(考虑无效输入:首先判断输入日期是否合法.) 闰年满足条件(year%4==0 && year%100!=0)||(year%400==0)
二.代码及注释:
#include<stdio.h>
#include<iostream>
using namespace std;
struct Date{
int year ;
int month ;
int day;
};
int runnian(int x){
int i;
if((x%400==0&&x%100!=0)||(x%400==0))
i= 1; //是闰年
else
i= 0;//不是闰年
return i;
}
void day(struct Date *p){
int n=0;
int i;
i=runnian(p->year );
if(i==0){//不是闰年
if(p->day==1){//每月的第一天
if(p->month==1){//一月 年份减一 月份变为12 日期变为31
p->year-=1;
p->month =12;
p->day=31;
}
else if(p->month==2||p->month==4||p->month==6||p->month==8||p->month==9||p->month==11){//前一月份是大月(有三十一天)的情况下
p->month-=1;
p->day=31;
}
else if(p->month==5||p->month==7||p->month==10||p->month==12){//前一月份是小月(有三十天)的情况下
p->month-=1;
p->day=30;
}
else if(p->month ==3){//三月份的情况 月份减一 天数变为28
p->month-=1;
p->day=28;
}
}
else//不是每月的第一天
p->day -=1;
}
if(i==1){
if(p->day==1){
if(p->month==1){
p->year-=1;
p->month =12;
p->day=31;
}
else if(p->month==2||p->month==4||p->month==6||p->month==8||p->month==9||p->month==11){
p->month-=1;
p->day=31;
}
else if(p->month==5||p->month==7||p->month==10||p->month==12){
p->month-=1;
p->day=30;
}
else if(p->month ==3){//三月份的情况 月份减一 天数变为29
p->month-=1;
p->day=29;
}
}
else
p->day -=1;
}
}
int main(){
struct Date t;
int days;
days=0;
cout<<" date: "<<endl;
scanf("%d%d%d",&t.year,&t.month,&t.day);
if(t.year>2020||t.year<1000||t.month<=0||t.month >12||t.day >32||t.day<=0){//年份范围在1000-2020 月份在0-12 天数不能在0-31天
printf("ERROR!\n");
return false;
}
else if(t.month==1||t.month==3||t.month==5||t.month==7||t.month==8||t.month==10||t.month==12){//大月份日期在1-31
if(t.day>31||t.day<=0){
printf("ERROR!\n");
return false;
}
}
else if(t.month==4||t.month==6||t.month==9||t.month==11){//小月份日期在1-30
if(t.day>30||t.day<=0){
printf("ERROR!\n");
return false;
}
}
else if(t.month==2){//判断闰年的二月的天数
int i;
i=runnian(t.year);
if(i==0){//不是闰年
if(t.day>28||t.day<=0){
printf("ERROR!\n");
return false;
}
}
if(i==1){//是闰年
if(t.day>29||t.day<=0){
printf("ERROR!\n");
return false;
}
}
}
day(&t);
printf("%d %d %d",t.year,t.month,t.day);
cout<<endl;
}