Easy way to keeping angles between -179 and 180 degrees

后端 未结 16 2662
长发绾君心
长发绾君心 2020-12-04 16:41

Is there an easy way to convert an angle (in degrees) to be between -179 and 180? I\'m sure I could use mod (%) and some if statements, but it gets ugly:


/         


        
16条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 17:21

    I'm a little late to the party, I know, but...

    Most of these answers are no good, because they try to be clever and concise and then don't take care of edge cases.

    It's a little more verbose, but if you want to make it work, just put in the logic to make it work. Don't try to be clever.

    int normalizeAngle(int angle)
    {
        int newAngle = angle;
        while (newAngle <= -180) newAngle += 360;
        while (newAngle > 180) newAngle -= 360;
        return newAngle;
    }
    

    This works and is reasonably clean and simple, without trying to be fancy. Note that only zero or one of the while loops can ever be run.

提交回复
热议问题