【发布时间】:2020-06-09 09:30:03
【问题描述】:
如果我想计算未来一周中的哪一天,结果很简单:
enum { SUNDAY = 0, MONDAY = 1/*....*/ SATURDAY = 6}
int getDayInFuture(int currentDay, int numDaysForward)
{
return (currentDay + numDaysForward) % 7;
}
But I have a function where you can enter a number of days either forward or backward, and I'm having trouble for when calculating a day in the past. The best I've done so far is:
inline int getDayInFutureOrPast(int currentDay, int numDaysForwardOrBack)
{
int result = (currentDay + numDaysForwardOrBack);
if (result >= 0) return result % 7; // JUST CALCULATE IT SIMPLY AS NORMAL
else // GOING BACKWARDS
{
int remainder = result % 7;
if (remainder == 0) return 0; // I HAVE TO ADD THIS SPECIAL CONDITION, IF I DON'T SUNDAY
// (enum 0) minus 7 days ends up as -7 + (-7 modulo 7) == 7
// SHOULD BE 0, SUNDAY(0) MINUS 7 DAYS SHOULD BE SUNDAY(0)
else return 7 + remainder;
}
}
我觉得有一种更简单的方法可以做到这一点,但我想不出。
【问题讨论】: