简体   繁体   English

C ++:获得两个月/年之间的范围

[英]C++: Getting the range between two months/years

In class, we're doing an assignment to get the range between two dates using months and years as input. 在课堂上,我们正在做一个分配,以使用月和年作为输入来获取两个日期之间的范围。

My process code is as follows: 我的流程代码如下:

    int totalMonths1 = (year * MONTHS_IN_YEAR) + month;
    int totalMonths2 = (year2 * MONTHS_IN_YEAR) + month2;
    int range;

    if(totalMonths1 > totalMonths2)
    {
        range = totalMonths1 - totalMonths2;
    }

    if(totalMonths1 < totalMonths2)
    {
        range = totalMonths2 - totalMonths1;
    }

With const int MONTHS_IN_YEAR = 12. 使用const int MONTHS_IN_YEAR = 12。

This tells me the difference between the two dates, but not the range. 这告诉我两个日期之间的差异 ,但没有范围。 If I add 1 to the result, it's the correct range according to my professor's example program, but I'd like to know if there's a better way to get the range instead of doing "difference + 1". 如果我将结果加1,则根据我的教授的示例程序,该范围是正确的范围,但我想知道是否有更好的方法来获取范围而不是执行“差+ 1”。

No. It doesnt get any simpler/better than a - b + 1 . 不。它没有比a - b + 1更简单/更好的选择。 Unfortunately, anything else is over-complicating the solution and unnecessary. 不幸的是,其他任何事情都使解决方案过于复杂,并且不必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM