C++ C++;:获取两个月/年之间的范围
在课堂上,我们做了一个作业,以月和年作为输入,得到两个日期之间的范围 我的流程代码如下:C++ C++;:获取两个月/年之间的范围,c++,C++,在课堂上,我们做了一个作业,以月和年作为输入,得到两个日期之间的范围 我的流程代码如下: int totalMonths1 = (year * MONTHS_IN_YEAR) + month; int totalMonths2 = (year2 * MONTHS_IN_YEAR) + month2; int range; if(totalMonths1 > totalMonths2) { range = totalMonths1 -
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;
}
int totalMonths1=(年*月+年)+月;
int TOTALLMONTHS2=(第2年*第2年的月份)+第2个月;
整数范围;
如果(totalMonths1>totalMonths2)
{
范围=总月数1-总月数2;
}
如果(总月数1<总月数2)
{
范围=总月数2-总月数1;
}
年内的常量int月=12
这告诉我两个日期之间的差异,但不是范围。如果我在结果中加1,根据我教授的示例程序,这是正确的范围,但我想知道是否有更好的方法来获得范围,而不是执行“差分+1”。否。它没有比
a-b+1
更简单/更好。不幸的是,其他任何事情都会使解决方案过于复杂,而且是不必要的 如果totalMonths1==totalMonths2
?你在寻找一个比a-b+1
更简单的表达式呢?使用range=abs(totalMonths1-totalMonths2)+1
@zenith我刚重写了几行,我忘了在第一个if语句中添加| totalMonths1==totalMonths2。@Nemo我的教授对一切都非常敏感。如果我使用+1,他会因为我没有使用常量int来表示1而给我打分,很可能是因为我根本没有使用常量int。