【问题标题】:What's the simplest way to calculate a day of the week forwards or backwards?向前或向后计算一周中某一天的最简单方法是什么?
【发布时间】: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;
    }
}

我觉得有一种更简单的方法可以做到这一点,但我想不出。

【问题讨论】:

    标签: modulus days


    【解决方案1】:

    将 currentDay 和 numDaysForwardOrBack 相加将给出所需的日期,但它不在 0 到 6 的范围内。对总和使用模将给我们 Sum/7 商的余数,但是这第一个模运算仍然可能给我们一个否定的结果。为了消除负面结果,我将结果加 7 并再次执行取模。这种二次加法运算不会改变一开始为正的结果,因为模数会去除多余的部分,而负值会向上移动到正值范围。

    inline int getDayInFutureOrPast(int currentDay, int numDaysForwardOrBack)
    {
        int remainder = (currentDay + numDaysForwardOrBack) % 7; // value range is [-6 to 6]
        return (7 + remainder) % 7; //shifts value up to bring value range to [0 to 6]
    }
    

    【讨论】:

    • 为了改进答案,请说明答案有效的原因
    • 添加说明
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多