问题描述
我有一个变量,它包含一个角度(以度为单位),该角度可以为正,也可以为负.现在,我需要确保此数字仅在0到360之间.这个数字是双精度数.
I have a variable that holds an angle, in degrees, which can be both positive and negative. I now need to make sure that this number is between 0 and 360 only. The number is a double.
一个好的算法会是什么?简单地执行角度%360无效,因为负数最终仍然是负数.奖金指向最小的算法(又名Code Golf).
What would a nice algorithm for doing that be? Simply doing angle % 360 does not work, because negative numbers end up still being negative. Bonus points to the smallest algorithm (aka, Code Golf).
显然,这在不同的语言中是不同的.在ActionScript和JavaScript中,取模将返回+ m和-m之间的数字:
Apparently this is different in different languages. In ActionScript and JavaScript, modulo will return a number between +m and -m:
(-5) % 360 = -5
推荐答案
d = ((d % 360) + 360) % 360;
如果取模的值在-359到359之间,则将起作用.
will work if modulo gives you a value between -359 and 359.
我个人将其放在一个单独的函数中,因为它像罪恶一样丑陋.
I'd personally put this in a separate function since it's as ugly as sin.
def mymodulo(n,m):
return ((n % m) + m) % m;
- 第一个模数的取值范围是-359至359.
- 该加法器将其增加到1到719之间.
- 第二个模将其带回您想要的范围,从0到359.
对于代码高尔夫球,包括Python中的换行符在内的29个字符:
For code golf, 29 characters including the newline in Python:
def f(n,m):return((n%m)+m)%m
并不是Python真正需要它:(-5)%360
用该语言为您提供355:-)
Not that Python actually needs it: (-5)%360
gives you 355 in that language :-)
这篇关于如何找到与i模m相等的最小正整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!