英文:
Algorithm to rotate a float value between 0 and 360 degrees by +180 degrees
问题
将一个浮点数(将介于0.0和360.0之间)旋转+180度。
因此,0.0将变为180.0
90.0将变为270.0
180.0将变为0.0
270将变为90.0
我正在考虑以下算法,但它似乎有点粗糙? 有没有更简单的方法:
如果数字小于180,则加上180
否则,如果数字大于180,则减去180。
英文:
I want to take a floating point number (which will be between 0.0 and 360.0) and rotate that value by + 180 degrees.
So 0.0 would become 180.0
90.0 would become 270.0
180.0 would become 0.0
270 would become 90.0
I am thinking of the following algorithm, but it seems a bit crude? Is there a simpler way?:
If number < 180 then add 180
else if number > 180 then subtract 180.
答案1
得分: 2
(number + 180) % 360
模除运算适用于整数,在某些语言中也适用于浮点数(如Python等)。还有像C++中的fmod
等特殊函数。
英文:
(number + 180) % 360
Modulo operation for integers, also works for floats in some languages (Python etc). There are also special functions like C++ fmod
答案2
得分: 1
"I think 'just code the your idea as is' is the simplest, and enough. Depending on the language, for example writing like (X<180 ? X+180 : X-180)
makes the code look simpler, but the meaning is the same.
I think, thinking some other less straightforward writing styles (e.g. X - 180 * ( (X>=180) - (X<180) )
) or employing operator that may be unnecessary expensive (e.g. modulo), will be nonsense."
英文:
I think "just code the your idea as is" is the simplest, and enough.
Depending on the language, for example writing like (X<180 ? X+180 : X-180)
makes the code look simpler, but the meaning is the same.
I think, thinking some other less straightforward writing styles (e.g. X - 180 * ( (X>=180) - (X<180) )
) or employing operator that may be unnecessary expensive (e.g. modulo), will be nonsense.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论