C++ 日期推算

【问题描述】

设计一个程序用于向后推算指定日期经过n天后的具体日期。

【输入形式】

  • 输入为长度为8的字符串str和一个正整数n,str前四位表示年份,后四位表示月和日。

【输出形式】

  • 当推算出的年份大于4位数时,输出"out of limitation!",否则输出8位的具体日期。

【样例输入1】

00250709 60000

【样例输出1】

01891017

【样例输入2】

扫描二维码关注公众号,回复: 17172458 查看本文章

19310918 5080

【样例输出2】

19450815

【样例输入3】

99980208 999

【样例输入3】

out of limitation!

【样例说明】

  • 日期的表示必须8位数,年月日不足长度需要添加前缀字符'0'。

  • 注意闰年和平年的2月份天数不同。

  • 注意判断输出信息是否符合要求。

 【完整代码如下】

#include<iostream>
#include<string.h>
using namespace std;
class Calculate
{
public:
	Calculate(int years,int months,int days,int ns):year(years),month(months),day(days),n(ns)
	{		
	}
	bool Judge();//判断是否为闰年 
	void AddOne();
	void AddDay();
	void show();
private:
	int year;
	int month;
	int day;
	int n;
};
bool Calculate::Judge() 
{
	if((year%400==0)||(year%100!=0&&year%4==0))
		return true;
	else
		return false;
}
void  Calculate::AddOne()
{
    if((month==1||month==3||month==5||month==7||month==8||month==10)&&(day==31))
    {
        day=1;
        month+=1;
    }
    else if((month==4||month==6||month==9||month==11)&&(day==30))
    {
        day=1;
        month+=1;
    }
    else if(month==12&&day==31)
    {
        day=1;
        month=1;
        year+=1;
    }
    else if(month==2&&day==29&&Judge())
    {
        day=1;
        month+=1;
    }
    else if(month==2&&day==28&&!Judge())
    {
        day=1;
        month+=1;
    }
    else
    {
        day+=1;
    }

}
void Calculate::AddDay()
{
    for(int i=0;i<n;i++)
    {
        AddOne();
    }
    if(year>9999)//判断推算出的年份大于4位数 
    {
        cout<<"out of limitation!"<<endl;
    }
    else
    {
        show();
    }
}
void Calculate::show()
{
    cout<<year<<month<<day<<endl;
}
int main()
{
	string str;
	int n;
	cin>>str;
	cin>>n;
	//把字符串里的日期信息转化为数字,方便后面的运算 
	int year = 1000 * (str[0] - 48) + 100 * (str[1] - 48) + 10 * (str[2] - 48) + (str[3] - 48);
//	cout<<year<<endl;
	int month = 10 * (str[4] - 48) + (str[5] - 48);
///	cout<<month<<endl;
	int day = 10 * (str[6] - 48) + (str[7] - 48);
//	cout<<day<<endl;
	Calculate t(year,month,day,n);
	t.AddDay();
	return 0;	
} 

猜你喜欢

转载自blog.csdn.net/weixin_74287172/article/details/134470091