将一个在0到360度之间的浮点值旋转+180度的算法

huangapple go评论54阅读模式
英文:

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&lt;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&gt;=180) - (X&lt;180) ) ) or employing operator that may be unnecessary expensive (e.g. modulo), will be nonsense.

huangapple
  • 本文由 发表于 2023年5月18日 02:36:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275237.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定