开发者

clockwise angle between two line

I want to calculate a clockwise angle between two line segment A and B. So the resulting angle must be between 0 to 360-1 degrees. I've seen all other answers in SO but they gave me negative angle开发者_运维知识库s. Thanks.


For turning any angle into a 0-359 range in C#, you can use the following "algorithm":

public int Normalise (int degrees) {
    int retval = degrees % 360;
    if (retval < 0)
        retval += 360;
    return retval;
}

C# follows the same rules as C and C++ and i % 360 will give you a value between -359 and 359 for any integer, then the second line is to ensure it's in the range 0 through 359 inclusive.

A sneaky version on one line:

    degrees = ((degrees % 360) + 360) % 360;

which would normalise it under all conditions. I'm not sure I'd worry too much about using the inline one-liner unless performance was critical, but I will explain it.

From degrees % 360, you will get a number between -359 and 359. Adding 360 will modify the range to between 1 and 729. Then the final % 360 will bring it back to the range 0 through 359.


I would try :

if degrees is between [-360, 360]
    degrees = (degrees + 360) % 360;
else degrees = (degrees % 360) + 360) % 360;


Surely you could adapt any solution with negative angles to always be 0-360 by adjusting:

float positive = (angle < 0) ? (360 + angle) : angle

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜