C++语言编写程序:前一日函数PreDate。实现功能为:输入1000 年到2020 年之间的某个日期(20180412),函数返回这一天的前一天的日期。(考虑无效输入:首先判断输入日期是否合法.)

一.题目:  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;



}

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值