Search code examples
c++decimalangle

Keeping a decimal number within a range


If I have a decimal number representing an angle and I add it to another angle, how can I ensure that it remains between 0° and 359°? So if it's 120° + 270°, it will be 30° instead of 390°? I could check if they are above or below the limit and then add or subtract 360°, but what if it ends up more than 360° out? I would use modulo, but I'm not sure how that would work with decimals and negative numbers. I could also use a loop that adds/subtracts 360 until it is in the range, but I'm not sure if that's a good idea. (I'm actually doing this with radians, it's just easier to explain with degrees)


Solution

  • You can use the modulus operation. With integers this is the % operator, with floats you can use std::fmod

    // \brief Calculates the sum of two angles
    // \param[in]  a  First angle [degrees]
    // \param[in]  b  Second angle [degrees]
    // \return Sum of two angles [degrees, [0, 360)]
    double AddAngles(double a, double b)
    {
        const double totalAngle = a + b;
        if (totalAngle >= 0.0)
        {
            return std::fmod(totalAngle, 360.0);
        }
        else
        {
            return 360.0 - std::fmod(-totalAngle, 360.0);
        }
    }
    

    Demo

    int main()
    {
        std::cout << AddAngles(30.0, 450.0) << std::endl
                  << AddAngles(50.0, 80.0) << std::endl
                  << AddAngles(180.0, 180.0) << std::endl
                  << AddAngles(-180.0, -270.0) << std::endl;
    }
    

    Output

    120
    130
    0
    270