首页 > 解决方案 > 修复日期类增量 (C++)

问题描述

我做了一个图书馆系统。但我刚刚检查了一下,我的“日期”工作不正常。

这堂课的首要任务

                                   (1) Increment date      

现在,我在递增日期遇到问题,当我将其递增到 25-30 的值时它工作正常。但是当我输入 90 时,它就搞砸了。

void increment_date(int num)
    {
        int day;
        int month_new;
        setDay(getDay()+num);


        if(    getDay()>Days_per_Month[getMonth()]     )
        {
            day=getDay()-Days_per_Month[getMonth()];
            setDay(day);
            setMonth(getMonth()+1);
            if(Days_per_Month[getMonth()]>12)
            {
                month_new=1;
                setMonth(month_new);
                setYear(getYear()+1);
            }
        }
        cout<<"Return Date: ";
        Print_Date();
    }
//the code below is outside the class.

const int Date:: Days_per_Month[13]={0,31,28,31,30,31,30,31, 31, 30, 31, 30, 31};
int Date::checkDay(int testday)     //returntype classname :: funcname (parameteres)
{
    //static const int Days_per_Month[13]={0,31,28,31,30,31,30,31, 31, 30, 31, 30, 31};
    if(testday > 0 && testday <= Days_per_Month[Month])
        return testday;
    if ( Month==2 && testday==29 && (Year%400==0 || (Year%4==0 && Year%100!=0)) )  //for leap year
        return testday;

    cout<<"Day "<<testday<<" invalid. Set to day 1."<<endl;
    return 1;
}

在此处输入图像描述

标签: c++

解决方案


    setDay(getDay()+num);

    if(    getDay()>Days_per_Month[getMonth()]     )
    {
        day=getDay()-Days_per_Month[getMonth()];
        setDay(day);
        setMonth(getMonth()+1);

在上面的代码中,你将num返回的值加上getDay(),然后你检查是否getDay()大于当月的天数,如果是,你尝试通过减去天数来纠正问题当前月份,然后递增月份。

到目前为止,一切都很好,但是如果getDay()在你做减法之后仍然大于当月的天数怎么办?(例如,如果用户输入300增量计数怎么办?)在这种情况下,您需要再次执行整个操作,并继续执行此操作,直到getDay()小到足以成为有效的月内日期值。所以真的需要一个while循环,而不仅仅是一个if.


推荐阅读