将角度保持在-179至180度之间的简便方法 [英] Easy way to keeping angles between -179 and 180 degrees
问题描述
是否有一种简单的方法可以将角度(以度为单位)转换为-179至180?我确定我可以使用mod(%)和一些if语句,但是它很难看:
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:
//Make angle between 0 and 360
angle%=360;
//Make angle between -179 and 180
if (angle>180) angle-=360;
似乎应该有一个简单的数学运算可以同时执行两个语句.我可能现在只需要为转换创建一个静态方法即可.
It just seems like there should be a simple math operation that will do both statements at the same time. I may just have to create a static method for the conversion for now.
推荐答案
我参加聚会有点晚了,但是...
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;
}
这有效并且相当干净和简单,而不必花哨.请注意,只能运行零个或while循环之一.
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.
这篇关于将角度保持在-179至180度之间的简便方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!