【问题标题】:adding dates in C++, using class在 C++ 中添加日期,使用类
【发布时间】:2020-01-22 16:04:10
【问题描述】:

我是编码新手... 我用 C++ 编写了一个代码来计算在日期、月份和年份添加新数字后的日期。但是,它变得太长了,如果日期超过 50,我的计算机将无法处理它。

如果有办法缩短它,您能给我一些建议吗?

#include <iostream>
class Date{
  int year; int month; int day;
}
public:
void set_date(int _year, int _month, int _day){
    year=_year;
    month=_month;
    day=_day;
}
void add_day(int inc){
    day+=inc;
}
void add_month(int inc){
    month+=inc;
}
void add_year(int inc){
    year+=inc;
}

void get_date(){
    while (day>31){
        if ((year%4)==0 && month==2 && day > 29){
            month+=1;day-=29;
        }
        else if(month==2 && day > 28){
            month+=1;day-=28;
        }
        else if((day>30)&&(month==4||month==6||month==9||month==11)){
            month+=1;day-=30;
        }
        else if((day>31)&&(month==3||month==5||month==7||month==8||month==10||month==12||month==1)){
            month+=1;day-=31;
        }
    }
    if (month>12){
        year+=month/12;
        month=month%12;
    }
    std::cout<<"year"<<year<<std::endl;
    std::cout<<"month"<<month<<std::endl;
    std::cout<<"day"<<day<<std::endl;
}

int main(){
    Date date;
    date.set_data(191,2,10);
    date.add_day(60);
    date.add_month(10);
    date.add_year(3);

    date.get_date();
    return 0;
}

【问题讨论】:

  • 如果您没有必要使用您的数据实现,您可以使用ctime,您可以添加时间,看看这个response
  • 如果 what “超过 50”?
  • 您是否尝试过调试您的程序?
  • 您的get_date() 没有else,而且您的条件看起来很复杂,很可能您错过了一个条件,因此您进入了无限循环。您需要学习如何调试代码,因为在阅读代码时很难发现类似的东西,但在使用调试器单步执行代码时却非常容易找到:What is a debugger and how can it help me diagnose problems?
  • 好的,谢谢,我昨天发现实际上是这样的......

标签: c++


【解决方案1】:

当我运行您的代码时,它会以 day=39 和 month=13 永远循环,这是您不检查的条件。您可能希望将整个 if (month&gt;12) 移动到您的循环中,以便在处理日期时更正月份。您还想添加一个停止循环的else

bool doneProcessing = false;
do
{
    if ((year % 4) == 0 && month == 2 && day > 29)
    {
        month += 1;
        day -= 29;
    }
    else if (month == 2 && day > 28)
    {
        month += 1;
        day -= 28;
    }
    else if ((day > 30) && (month == 4 || month == 6 || month == 9 || month == 11))
    {
        month += 1;
        day -= 30;
    }
    else if ((day > 31) && (month == 3  ||  month == 5 || month == 7 || month == 8 || month == 10 || month == 12 || month == 1))
    {
        month += 1;
        day -= 31;
    }
    else
    {
        doneProcessing = true;
    }
    if (month > 12)
    {
        year += month / 12;
        month = month % 12;
    }
}
while (!doneProcessing);

我没有检查你的语义的有效性,但我确实注意到一件事:当你有月份=2 和天=30 时,你也想处理它,但你只检查天>31,因此我将循环更改为简单地运行直到else 被击中(现在所有日期都有效)。

通过此更改,您的代码将在打印此结果后正确终止:

195 年
月2
第8天

PS:使用调试器,您可以轻松快速地找到此类问题。见What is a debugger and how can it help me diagnose problems?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-15
    • 1970-01-01
    • 2011-08-31
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多