[英]C# - Clamping an angle vs using modulo
What is the difference between clamping an angle like in the following code 如下面的代码所示,夹角之间有什么区别
do
{
if(angle < -360)
{
angle += 360;
}
if(angle > 360)
{
angle -= 360;
}
}while(angle < -360 || angle > 360);
... and using the modulo arithmetics; ...并使用模运算;
angle = angle % 360;
... and if this is relevant for the Unity game engine. ...,如果这与Unity游戏引擎有关。
Assuming angle
is an integer, the difference is that your clamp code allows angles of exactly -360
or +360
degrees. 假设
angle
是整数,则不同之处在于您的钳位代码允许的角度恰好为-360
或+360
度。 Modulo would reduce that to zero. 模可将其减少为零。
The comments speak of a difference in handling negative values. 这些评论谈到在处理负值方面的差异。 Those comments are wrong.
这些评论是错误的。 Both approaches would leave
-10
as -10
. 两种方法都将
-10
保留为-10
。
If angle
isn't an integer type though, if it's double
for instance, the %
operator may give different results than repeated addition or subtraction, due to repeated addition or subtraction introducing rounding problems. 但是,如果
angle
不是整数类型,例如,如果它是double
类型,则%
运算符可能会给出与重复加法或减法不同的结果,这是由于重复加法或减法会导致舍入问题。 In that case, the %
operator would be a better match. 在这种情况下,
%
运算符会更好。 You'd need excessively large angles for this to become a problem though, and with those excessively large angles, you don't have enough precision to represent angles accurately anyway. 但是,您需要过大的角度才能解决这个问题,而对于那些过大的角度,无论如何您都没有足够的精度来准确表示角度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.